'How can you get the selected option of a dropdown with Playwright

I am using the C# Language Bindings of Playwright.

Example HTML:

<select id="txtType" name="Type" class="form-control">
        <option>Blog Posts</option>
        <option>Books</option>
        <option>Presentations</option>
        <option>Videos</option>
        <option>Podcasts</option>
        <option>Examples</option>
</select>

I know that I can use Page.SelectOptionAsync to set the selected option for the dropdown, but how do I get the currently selected ones?

When I have a look at all of the properties of the DropDown, I can't see any difference in the ElementHandles.



Solution 1:[1]

<select id="element_id">
  <option value="1">Option 1</option>
  <option value="2" selected>Option 2</option>
<select>

For NodeJS Playwright

To get the selected option value (2) from the dropdown:

await page.$eval('#element_id', sel => sel.value)

To get the selected option text ("Option 2") from the dropdown:

await page.$eval('#element_id', sel => sel.options[sel.options.selectedIndex].textContent)

For C# just wrap the second argument in quotes:

await page.EvalOnSelectorAsync<string>("#element_id", "sel => sel.value")
await page.EvalOnSelectorAsync<string>("#element_id", "sel => sel.options[sel.options.selectedIndex].textContent")

Solution 2:[2]

You can use EvalOnSelectorAsync, passing a CSS selector, and function expecting that element and returning the value of that element:

await page.EvalOnSelectorAsync<string>("#txtType", "el => el.value")

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 Artur A
Solution 2 hardkoded