Jacob Staggs
Jacob Staggs

Reputation: 13

Puppeteer Click on Input with type of Checkbox

I have this element I am trying to click on

<input aria-checked="false" type="checkbox" data-reach-custom-checkbox-input="">

I am trying to do something like this but cannot seem to figure it out:

  const [check] = await page.$x('input[type="checkbox"]')
  if(check) {
    console.log("we have a check")
    check.click();
  }

Anyone have any advice on what to do? I can click on buttons in a similar fashion. Here is an example of a working button:

  const [button] = await page.$x("//button[contains(., 'Import')]");
  if (button) {
    await button.click();
  }

Upvotes: 1

Views: 2378

Answers (1)

Silvan Bregy
Silvan Bregy

Reputation: 2734

The checkbox can be clicked very similar to a button. This code worked for me so far:

const check = await page.$('input[type="checkbox"]')
await check.click()

Here is a fully working sandbox example:

import * as puppeteer from 'puppeteer'

const html = `
<input aria-checked="false" type="checkbox" data-reach-custom-checkbox-input="">
`
// utility
const wait = (ms) => {
    return new Promise(res =>
        setTimeout(res, ms)
    )
}

const main = async () => {
    const browser = await puppeteer.launch({ headless: false })
    const page = await browser.newPage()

    await page.setContent(html)

    console.log('Waiting before clicking..')
    await wait(4 * 1000)
    const check = await page.$('input[type="checkbox"]')

    await check.click()

    console.log('checkbox now checked. Waiting 10 Secs before shutdown')
    await wait(10 * 1000)

}

main()


Upvotes: 1

Related Questions