how do you loop through checkboxes using puppeteer?

664 Views Asked by At

I have a list of checkboxes , every time puppeteer run the test I need to :

  • if a box is already selected then move to next box and select it , and if the next is selected move to the next checkbox and so on

checkboxes sample

if(await page.$eval(firstcheckbox, check=>check.checked =true)) { //check if the box is selected await page.waitForSelector(do something, ele=>elem.click())//if the checkbox is already selected , move to the second row and select a undecked box

}else if{

await page.$eval(firstcheckbox, check=>check.checked =false)){ //if the checkbox is not ticked await page.$eval(clickcheckbox, elem=>elem.click);//tick the checkbox

1

There are 1 best solutions below

0
On

You can use all the testing and changing inside one page.evaluate():

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: false, defaultViewport: null });

const html = `
  <!doctype html>
  <html>
    <head><meta charset='UTF-8'><title>Test</title></head>
    <body>
      <input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1</label><br>
      <input type="checkbox" id="checkbox2" checked><label for="checkbox2">checkbox2</label><br>
      <input type="checkbox" id="checkbox3" checked><label for="checkbox3">checkbox3</label><br>
      <input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4</label><br>
    </body>
  </html>`;

try {
  const [page] = await browser.pages();

  await page.goto(`data:text/html,${html}`);

  await page.evaluate(() => {
    for (const checkbox of document.querySelectorAll('input')) {
      if (!checkbox.checked) checkbox.click();
    }
  });
  console.log('Done.');
} catch (err) { console.error(err); }

Or, if you need a loop over element handles, you can try this:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: false, defaultViewport: null });

const html = `
  <!doctype html>
  <html>
    <head><meta charset='UTF-8'><title>Test</title></head>
    <body>
      <input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1</label><br>
      <input type="checkbox" id="checkbox2" checked><label for="checkbox2">checkbox2</label><br>
      <input type="checkbox" id="checkbox3" checked><label for="checkbox3">checkbox3</label><br>
      <input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4</label><br>
    </body>
  </html>`;

try {
  const [page] = await browser.pages();

  await page.goto(`data:text/html,${html}`);

  for (const checkbox of await page.$$('input')) {
    if (!await checkbox.evaluate(elem => elem.checked)) {
      await checkbox.click();
    }
  }
  console.log('Done.');
} catch (err) { console.error(err); }