How to show selected options from dropdown of multiple selectors using selenium java?
I am trying to show all selected options in a dropdown with multiple choices. But don't get the right way to do it. Please help me with this.
Here is the html code for the dropdown:
<select multiple id="fruits">
<option value="banana">Banana</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="grape">Grape</option>
</select>
Here is the code I'm trying to use:
public void dropDownOperations()
{
driver.get("http://output.jsbin.com/osebed/2");
Select DDLIST = new Select(driver.findElement(By.id("fruits")));
DDLIST.selectByIndex(0);
String currentvalue = DDLIST.getFirstSelectedOption().getText();
System.out.println(currentvalue);
DDLIST.selectByIndex(1);
String currentvalue1 = DDLIST.getFirstSelectedOption().getText();
System.out.println(currentvalue1);
}
I also tried with this code:
Here's how I get this output:
[[[[[ChromeDriver: chrome on XP (69aee19e9922ca218ff47c0ccdf1bbbc)] → id: fruits]] → tag name: option], [[[[[ChromeDriver: chrome on XP (69aee19e9922ca218ff47c0ccdf1bbbc)] → id name: fruits]] → tag: option]]
public void dropDownOperations1()
{
driver.get("http://output.jsbin.com/osebed/2");
Select DDLIST = new Select(driver.findElement(By.id("fruits")));
DDLIST.selectByIndex(0);
DDLIST.selectByIndex(1);
List<WebElement> currentvalue1 = DDLIST.getAllSelectedOptions();
System.out.println(currentvalue1);
}
source to share
Your second approach should work fine with a minor fix. getAllSelectedOptions()
will return a list of selected options as a WebElement. You need to loop over the list to get the text from the WebElement.
List<WebElement> selectedOptions = DDLIST.getAllSelectedOptions();
for (WebElement option : selectedOptions){
System.out.println(option.getText());
}
source to share
Try this below code, it will select one by one from the dropdown.
Select DDLIST = new Select(driver.findElement(By.id("fruits")));
DDLIST.selectByIndex(0);
DDLIST.selectByIndex(1);
List<WebElement> selectedOptions = DDLIST.getAllSelectedOptions();
for(int i=0; i<selectedOptions.size(); i++)
{
System.out.println(DDLIST.getOptions().get(i).getText());
}
source to share