Reputation: 23800
Assume I have this html code:
<select id="superior" size="1" name="superior">
<option value=""></option>
<option value="c.i.e.m.md.Division_1">DIVISION007</option>
<option selected="selected" value="c.i.e.m.md.Division_$$_javassist_162_119">MyDivision</option>
<option value="c.i.e.m.md.Division_121">MyDivision4</option>
<option value="c.i.e.m.md.Division_122">MyDivision5</option>
</select>
So this is a combo box with
id=superior
and currently value MyDivision is selected.
Using Selenium WebDriver I am trying to get the selected value, but no success.
I tried:
String option = this.ebtamTester.firefox.findElement(By.id(superiorId)).getText();
return option;
But this returns me all the values in the combobox.
Help please?
Edit:
WebElement comboBox = ebtamTester.firefox.findElement(By.id("superior"));
SelectElement selectedValue = new SelectElement(comboBox);
String wantedText = selectedValue.getValue();
Upvotes: 10
Views: 58802
Reputation: 1
Based off @Micheal's answer this would be easier to work with following command:
string selectedValue = new SelectElement(driver.FindElement(By.Id("Year"))).SelectedOption.Text;
Upvotes: -1
Reputation: 1739
selectedValue.SelectedOption.Text; will get you the text of the selected item. Does anyone know how to get the selected value.
To get the selected value use
selectedValue.SelectedOption.GetAttribute("value");
Upvotes: 4
Reputation: 15973
Using XPath in c#
string selectedValue=driver.FindElement(By.Id("superior")).FindElements(By.XPath("./option[@selected]"))[0].Text;
Upvotes: 3
Reputation: 37796
In Java, the following code should work nicely:
import org.openqa.selenium.support.ui.Select;
Select comboBox = new Select(driver.findElement(By.id("superior")));
String selectedComboValue = comboBox.getFirstSelectedOption().getText();
System.out.println("Selected combo value: " + selectedComboValue);
As MyDivision is selected currently, the above code would print "MyDivision"
Upvotes: 9
Reputation: 3404
To select an option based on the label:
Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");
To get the first selected value:
WebElement option = select.getFirstSelectedOption()
Upvotes: 3
Reputation: 1220
This is written in C#, but it shouldn't be hard to transition it over to any other language you're using:
IWebElement comboBox = driver.FindElement(By.Id("superior"));
SelectElement selectedValue = new SelectElement(comboBox);
string wantedText = selectedValue.SelectedOption.Text;
SelectElement requires you to use OpenQA.Selenium.Support.UI, so at the top, type
using OpenQA.Selenium.Support.UI;
Edit:
I suppose for you, instead of 'driver' you would use
IWebElement comboBox = this.ebtamTester.firefox.FindElement(By.Id("superior"));
Upvotes: 19