How to set value of select with node Puppeteer

I am trying to do some automation with the rather new GoogleChrome/puppeteer library, but I cannot figure out how to set a value in a select field.

Here is my (simplified) function to set the value of a text input:

async function setInputVal(sel, text) {
    await page.focus(sel)        
    page.press('Backspace')
    page.type(text)
}

await setInputVal('input.searchjob', task.id)

I cant figure out how to do the same for a select field.

I have tried to set the focus, insert script and execute but I cannot get it working.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I found a solution myself:

async function setSelectVal(sel, val) {
    page.evaluate((data) => {
        return document.querySelector(data.sel).value = data.val
    }, {sel, val})
}

await setSelectVal('#select_id', 'newValue')

Solution 2

You can use page.select() to select an option:

await page.select('select#example', 'carrot');

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply