3

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

user2611836
  • 386
  • 4
  • 6
  • 17

3 Answers3

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

public String readField() {
   Select select = new Select(editSubOrg_timezone);
   WebElement tmp = select.getFirstSelectedOption();
   return tmp.getText();  
}
nilesh
  • 14,131
  • 7
  • 65
  • 79
1

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;  
}
Code Enthusiastic
  • 2,827
  • 5
  • 25
  • 39
0

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;
}
dmeehan
  • 2,317
  • 2
  • 26
  • 31