Thursday, May 8, 2014

How to select 1st option from all the dorpdown.


Select class can not be used always to select the option from dropdown. Select class can be used only when the dropdown menu has been created using <select> tag.
So for other scenario, 1st you can click on dropdown menu and then you can click on the particular option, either after moving the cursor over option then click or directly click on the option.

Note- Here for the 1st dropdown we can select the 1st element but for the rest the 1st element is blank so selecting the 2nd option.

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SelectFirstValueFromAllDropdown {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://regtest.gmail.co.za/#top");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        List<WebElement> ele = driver.findElements(By.xpath("//select[@class='form-input']"));
        for(int i=0; i<ele.size(); i++){
           
            Select sel = new Select(ele.get(i));
            if(i==0){
                sel.selectByIndex(0);
            }else{
                sel.selectByIndex(1);
            }
        }
        WebElement where = driver.findElement(By.xpath("//select[@id='demogscp']"));
        Select sel1 = new Select(where);
        sel1.selectByIndex(1);
        List<WebElement> date = driver.findElements(By.xpath("//td//select[contains(@id,'date')]"));
        for(int i=0; i<date.size(); i++){
            Select sel = new Select(date.get(i));
            sel.selectByIndex(0);
        }
    }
}

No comments:

Post a Comment