Hi there! Today, I would like to discuss about how to work with drop-down list.
Package org.openqa.selenium.support.ui.Select allows us to work with drop-down lists.
- Example 1
public static List<String> getAllOptions(WebElement element) {
//initialize object select
Select select = new Select(element);
//create list of WebElements
List<WebElement> options = select.getOptions();
List<String> optionsText = new ArrayList<>();
//iterate a list
for(int i=0; i<options.size(); i++) {
//get text of each element
String text = options.get(i).getText();
optionsText.add(text);
}
2. Example 2
public static void selectValueFromDropDownWithOptions(WebElement element, String selectValue) {
List<WebElement> options = select.getOptions();
for(int i=0; i<options.size(); i++) {
String value = options.get(i).getText();
System.out.println(value);
if(value.equals(selectValue)) {
options.get(i).click();
break;
}
}
}
3. Example 3
public static void selectValueFromDropDown(List<WebElement> optionsList, String value) {
//criate variable int size
int dayCount = optionsList.size();
System.out.println(dayCount);
//itarte list
for(int i=0; i<dayCount; i++) {
//get text from each element
String optinalVal = optionsList.get(i).getText();
System.out.println(optinalVal);
//if May == May
if(optinalVal.equals(value)) {
optionsList.get(i).click();
//break the looop
break;
}
}
}