How to retrieve a selected value from a list box?

HTML Content:

<select id="modalNewUser-body-information-timeZone" class="span12 ng-valid ng-dirty" ng-options="timezone for timezone in timezoneList" ng-model="newUser().timeZone" uid="timeZone" name="timezone">
    <option selected="" value="">-- Select One --</option>
    <option value="0">AST</option>
    <option value="1">EST</option>
    <option value="2">CST</option>
    <option value="3">MST</option>
    <option value="4">PST</option>
    <option value="5">YST</option>
    <option value="6">HST</option>
</select>

suppose I have selected 'EST' from the list box How can I retrieve it? I am not able to retrieve with getFirstSelectedOption().getText()

Select select = new Select(driver.findElement(By.id("modalNewUser-body-information-timeZone"))); select.selectByVisibleText("EST"); String timeZone = select.getFirstSelectedOption().getText();

Upvotes: 0

Views: 2888

Answers (3)

Abhishek Yadav
Abhishek Yadav

Reputation: 459

The code provide by you is working fine for me.

Could you please update your selenium version and try again?

Following is the tested code:

Select select = new Select(abhiDriver.findElement(By.id("modalNewUser-body-information-timeZone")));
select.selectByVisibleText("EST");
String timeZone = select.getFirstSelectedOption().getText();
System.out.println(timeZone);

Upvotes: 0

Amit Prajapati
Amit Prajapati

Reputation: 1190

You can try this:

$("#modalNewUser-body-information-timeZone option:selected").text();

Upvotes: 0

autoKarma
autoKarma

Reputation: 839

It is my understanding that you can only use Select elements when there is actually a 'select' tag. Often times, things that look like drop down boxes don't truly behave like Select elements. What if you tried to get the text this way (I'm C# here, but Java just has different capital letters for this, I believe):

string timeZone = driver.FindElement(By.XPath("//option[@value = '1']")).Text;

expected return: "EST"

Upvotes: 1

Related Questions