How to Handle Autocomplete in Playwright

Profile picture for user devraj

In an application, you will find autocomplete widget associated with a textbox or search box. The Autocomplete provides suggestions while you type into the field and allows you to select the value from the dropdown. Examples are the google search box and amazon search box.

Table of Contents

  1. Demo Website
  2. Example
  3. Video Tutorial

Demo Website

For the demo, let's select the "dell laptop bag" value from the amazon search dropdown after typing "dell laptop."

How to Handle Autocomplete in Playwright


test.only('auto drop', async ({page})=>{
    await page.goto('')
    const searchValue = "dell laptop";
    const expectedValue = "dell laptop bag";
    // Type in search box
    await page.locator("input#twotabsearchtextbox").type(searchValue, {delay:100})

    // locator for suggested values
    const options = page.locator("div.autocomplete-results-container div.s-suggestion-container")
    //count suggested value
    const optionsCount = await options.count()
    // Iterate through each value 
    for(let i = 0; i < optionsCount; i++)
        // Get text of nth value
        const text = await options.nth(i).textContent();
        // if text matches the expected value
            // click and break lloop
            await options.nth(i).click()

Here we are typing dell laptop in the search box and clicking on dell laptop bag from the list of values. Delay is needed in some cases where auto-suggestion does not appear when we type the whole word.