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

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


Solution 1:[1]

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"

Solution 2:[2]

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");

Solution 3:[3]

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()

Solution 4:[4]

Using XPath in c#

  string selectedValue=driver.FindElement(By.Id("superior")).FindElements(By.XPath("./option[@selected]"))[0].Text;

Solution 5:[5]

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;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ripon Al Wasim
Solution 2 Peter Kerr
Solution 3 some_other_guy
Solution 4 Zain Ali
Solution 5 ZZZ