Need to Find Number of DropDown Options which are not selected.
URL : http://output.jsbin.com/osebed/2
TASK:
- Select Even Option available in fruits (Banana and Orange)
- Find out number of option not selected (Apple and Grape)
I tried it and could able to print Selected options (Banana and Orange) but cannot able to print Not Selected options (Apple and Grape)
Code:
public class Ques12 {
public static void main(String[] args) throws AWTException {
ChromeOptions options = new
ChromeOptions();
options.addArguments("--remote-allow-origins=*");
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
Robot robot = new Robot();
driver.get("http://output.jsbin.com/osebed/2");
WebElement Fruits = driver.findElement(By.id("fruits"));
Select select = new Select(Fruits);
select.selectByIndex(0);
select.selectByValue("orange");
List < WebElement > list = select.getOptions();
List < WebElement > selectedOptions = select.getAllSelectedOptions();
for (WebElement i: selectedOptions) {
for (WebElement j: list) {
if ((j.getText()).equals(i.getText())) {
System.out.println("Selected option " + j.getText());
} else {
System.out.println("Not selected option " + j.getText());
}
}
}
}
}
Output:
Selected option Banana
Not selected option Apple
Not selected option Orange
Not selected option Grape
==========================
Not selected option Banana
Not selected option Apple
Selected option Orange
Not selected option Grape
This logic below in your code is wrong
List<WebElement> list = select.getOptions();
List<WebElement> selectedOptions = select.getAllSelectedOptions();
for (WebElement i : selectedOptions) {
for (WebElement j : list) {
Simply use isSelected()and go through complete list only once to check for isSelected and print accordingly
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
Robot robot = new Robot();
driver.get("http://output.jsbin.com/osebed/2");
WebElement Fruits = driver.findElement(By.id("fruits"));
Select select = new Select(Fruits);
select.selectByIndex(0);
select.selectByValue("orange");
List<WebElement> list = select.getOptions();
for (WebElement j : list) {
if (j.isSelected()) {
System.out.println("Selected option " + j.getText());
} else {
System.out.println("Not selected option " + j.getText());
}
}
driver.quit();
Should Print
Selected option Banana
Not selected option Apple
Selected option Orange
Not selected option Grape