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.
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)
You can use selectedIndex to select the first option in a select dropdown menu:
await page.evaluate( () =>
{
    document.getElementById( 'select_id' ).selectedIndex = 0;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With