Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an option from dropdown select when value isn't known, using puppeteer

I am trying to select the first element in a dropdown using puppeteer. The problem is that the value of the option changes every test, so I cannot select the option based off of the value unless I can retrieve that value first.

Currently using:

await page.evaluate(() => {
  document.querySelector('#select_id > optgroup:nth-child(1) > option:nth-child(1)').selected = true;
});

This selects the option, however the dropdown item MUST be clicked in order for the form to submit (I do not have control over this).

I have additionally tried using Puppeteer keyboard commands to arrow down and hit enter but that functionality was not working for some reason.

like image 971
J. E Avatar asked Oct 26 '25 09:10

J. E


2 Answers

Using selected = true on item or selectedIndex = 0 on select will not trigger the change event so it will not submit your form.

I faced a similar issue and solved it with that method (using page.evaluate and page.select):

// Get the value of the first element
const value = await page.evaluate(() => {
  return document.querySelector('#select_id option:nth-child(1)').value
})

// Use it with page.select to select the item and trigger the change event
page.select('#select_id', value)
like image 146
Finrod Avatar answered Oct 27 '25 23:10

Finrod


You can use selectedIndex to select the first option in a select dropdown menu:

await page.evaluate( () =>
{
    document.getElementById( 'select_id' ).selectedIndex = 0;
});
like image 44
Grant Miller Avatar answered Oct 28 '25 00:10

Grant Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!