Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 519
BrendanMullins Avatar asked Aug 21 '17 07:08

BrendanMullins


2 Answers

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')
like image 130
BrendanMullins Avatar answered Oct 12 '22 23:10

BrendanMullins


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

await page.select('select#example', 'carrot');
like image 34
Grant Miller Avatar answered Oct 12 '22 23:10

Grant Miller