BruceyBandit
BruceyBandit

Reputation: 4324

How to grab text from a selected drop down value

I have the below HTML for a drop down menu:

<select class="" data-id-title="" default-selected="0" 
  data-bind="value: selectedTitle, options: titles, optionsText: 'Text', optionsValue:'ValueId',
  optionsCaption: 'Title', $el: $elTitle, hasFocus: titleHasFocus, attr: {'default-selected': defaultTitle}">
    <option value="">Title</option>
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="4">Miss</option>
    <option value="3">Ms</option>
</select>

I want to grab the text of the selected value of the drop down. So for example if I selected 'Mrs' from the title, I want to grab the text 'Mrs'.

Currently I am grabbing by value, so I am grabbing '2' as the output and not 'Mrs'. How do I grab the text?

Below is the code that is currently grabbing the selected drop down value:

public List<string> GetPassengerNames()
{
    List<string> titleList = new List<string>();

    var passengerTitles =  _driver.FindElements(PassengerDetailsElements.TitleField);

    foreach (var passengerTitle in passengerTitles)
    {
        titleList.Add(passengerTitle.GetAttribute("value"));
    }
    return titleList;
}

PassengerDetailsElements.TitleField is this:

public static By TitleField => By.XPath("//*[@data-id-title='']");

Thanks

Upvotes: 0

Views: 94

Answers (3)

iamsankalp89
iamsankalp89

Reputation: 4739

You can use like this, first use SelectElement to locate the dropdown

SelectElement drpDown= new SelectElement(driver.FindElement(By.Xpath("//*[@data-id-title='']")));
drpDown.SelectByText("Mr");

for text

selectedValue.SelectedOption.GetAttribute("value");

You can use official document of the selenium dropdown selection

Upvotes: 1

cle-b
cle-b

Reputation: 109

You can use the attribute selectedIndex for the select node in order to find which option is selected. Then, you can find the corresponding text.

my_select = driver.find_element_by_tag_name("select")
my_select.find_elements_by_tag_name("option")[int(my_select.get_attribute("selectedIndex"))].text

Upvotes: 0

tomasz.myszka
tomasz.myszka

Reputation: 111

  1. Select this option which you want

    SelectElement selectElement = new SelectElement(element); selectElement.SelectByText(text);

  2. After that, get a text

    new SelectElement(_casualtySearchPageElements.CasualtyWeather).SelectedOption.Text;

Upvotes: 0

Related Questions