user2611836
user2611836

Reputation: 416

Selenium Webdriver Java: how to get the visible text in dropdown menu from the value?

I am working with the following dropdown menu:

<select id="id_time_zone" name="time_zone" onchange="validate_field($(this), [validate_required])">
    <option value="">Please Select</option>
    <option value="1">UTC-12</option>
    <option value="2">UTC-11</option>
    <option value="3">UTC-10</option>
    <option value="4">UTC-9</option>
    </select>

What I am trying to do: I am trying to write a program that returns the current text that is selected. For example, if "UTC-12" is selected, my method would return String timezone="UTC-12."

What I have tried so far:

@FindBy(id = "id_time_zone")
WebElement editSubOrg_timezone;

// Reads and returns field
public String readField() {
tmp = editSubOrg_timezone.getText();
return tmp;  
}

Does not work, getText() returns all values in dropdown

@FindBy(id = "id_time_zone")
WebElement editSubOrg_timezone;

// Reads and returns field
public String readField() {
tmp = editSubOrg_timezone.getAttribute("value") ;
return tmp;  
}

Does not work, getAttribute("value") returns the the value (ie 1,2,3,4), not the corresponding displayed text

Upvotes: 3

Views: 24569

Answers (3)

dmeehan
dmeehan

Reputation: 2357

I use the following method (in C#) to get the text of the selected item:

public string getSelectedLabel(ddlDropListID)
{
   string selected;
   SelectElement selectOption = new SelectElement(ddlDropListID);
   selected = selectOption.SelectedOption.Text;
   return selected;
}

Upvotes: 0

Code Enthusiastic
Code Enthusiastic

Reputation: 2847

The method isSelected() returns true if an element is selected. Element can be either an element in a drop-down list or a check-box or a radio-button.

 @FindBy(id = "id_time_zone")
WebElement editSubOrg_timezone;

// Reads and returns field
public String readField() {
   List<WebElement> options = editSubOrg_timezone.findElements(By.tagName("option"));
   for (WebElement option : options) {
      if (option.isSelected) {
           return option.getText();
      }
   }
   return null;  
}

Upvotes: 1

nilesh
nilesh

Reputation: 14279

@FindBy(id = "id_time_zone")
WebElement editSubOrg_timezone;

public String readField() {
   Select select = new Select(editSubOrg_timezone);
   WebElement tmp = select.getFirstSelectedOption();
   return tmp.getText();  
}

Upvotes: 2

Related Questions