How to handle input fields and buttons in puppeteer

How to enter text in the input fields or a text filed and click on a button using puppeteer?

These are the very basic feature of any automation tool. Let’s explore some examples to enter data in input fields using puppeteer.

How to enter data in an input field using puppeteer

type(“Selector”, “Value”) is used to send value to any input fields in puppeteer.

await page.type("Selector", "Value");

clear input field in puppeteer

Sometimes we need to clear the input field before entering any data. In puppeteer does not have any predefined function yet to clear input filed but we can achieve this in some ways. below is the custom function to clear input field in puppeteer

async function clear(page, selector) {
  await page.evaluate(selector => {
    document.querySelector(selector).value = "";
  }, selector);
}

How to click on a button using puppeteer

click() is used to click on any element or button in the puppeteer. the only challenging thing with this is finding the element. Once you got the element just fire the click() function.
const searchBtn =  await page.$x("//button[@name='submit_search']");
searchBtn[0].click();

puppeteer example to use input and button

In this example, we Will see a test case where we are going to execute the following steps.

  • Launch browser.
  • Enter URL.
  • Search product.
const puppeteer = require('puppeteer')

describe("Home Page TestSuite",()=>{
     it("Handle Input and buuton in puppeteer",async()=>{
    const browser = await puppeteer.launch({
      headless:false,
      slowMo:100
    })
    const page = await browser.newPage()
    await page.goto("https://devexpress.github.io/testcafe/example/");

    //Enter value in the input
    await page.type("#developer-name", "Bhupendra Patidar");

    //Click on the pupulate button
   const searchBtn =  await page.$x("//*[@id='populate']");
   searchBtn[0].click();

   await page.close();

  });

    });