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);
Share
Improve this question
edited Sep 17, 2023 at 15:22
Anton Kesy
8262 gold badges11 silver badges18 bronze badges
asked Sep 17, 2023 at 15:11
MukhaMukha
3131 gold badge3 silver badges8 bronze badges
2 Answers
Reset to default 4To 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")