I can set value in the select dropdown. But when I call textContent, it returns all options values. My task is to verify that the set value is selected properly by extracting the value and checking it.
Is there any support for it in Playwright JS?
I tried different solutions.
One of them is below, but it didn't work
const selectedOptionText = await page.$eval(
`${selector_value_here} option:checked`,
(option) => option.textContent
);
console.log('Selected option text:', selectedOptionText);
I can set value in the select dropdown. But when I call textContent, it returns all options values. My task is to verify that the set value is selected properly by extracting the value and checking it.
Is there any support for it in Playwright JS?
I tried different solutions.
One of them is below, but it didn't work
const selectedOptionText = await page.$eval(
`${selector_value_here} option:checked`,
(option) => option.textContent
);
console.log('Selected option text:', selectedOptionText);
To get the selected value from dropdown:
For example, if your HTML is:
<select id="my-dropdown">
<option value="option1">Option 1</option>
<option value="option2" selected>Option 2</option>
<option value="option3">Option 3</option>
</select>
You can retrieve the selected value like this:
const selectedValue = await page.locator('#my-dropdown').evaluate(select => select.value);
console.log(selectedValue); // Output: "option2"
To validate selected value:
const dropdown = page.locator('#my-dropdown');
await expect(dropdown).toHaveValue('Option 2')
You may use evaluate https://playwright.dev/python/docs/next/api/class-worker#worker-evaluate
locator.evaluate("el => el.options[el.selectedIndex].text")