How to get the selected value from a combobox using Selenium WebDriver (Selenium 2)?

Viewed 56978

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();
6 Answers

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;
Related