Search code examples
node.jscomboboxlistboxpuppeteer

How to expand a combobox/listbox to select an option by its span text value? I have working code to select the option but the combobox cannot expand


I am trying to expand a combobox/listbox in a website. If i work off the console for the website and use

let countylocation = 'Cook County - Municipal Civil - District 2 - Skokie';

await page.evaluate((countylocation) => {
    Array.from(document.querySelectorAll('span')).filter(li => {
        return li.innerText == countylocation
    }).forEach(element => {
        if (element) element.click(); // click on il with specific text
    });
}, countylocation);

This works perfectly to select that option, but i have to physically click on the list box first, so that it expands, and allows me to select any of the span/text options.

What i have noticed before clicking on it is:

before

Once its clicked, its aria attributes change to:

after

What i have tried doing was

await page.evaluate(() => {document.querySelector("body > ngb-modal-window > div > div > app-case-search-filter-modal > div > form > div.modal-body > div > div > app-searchable-dropdown-field > div > div.form-group.ng-pristine.ng-invalid.ng-touched > div > span > ng-select > div > div > div.ng-input").click() });

But that yields an "undefined" error. It seems that this listbox can only be physically clicked and not programmatically.

I have also tried to expand its attribute of aria-expanded = true, but it still gives me back an undefined error.

document.querySelector("body > ngb-modal-window > div > div > app-case-search-filter-modal > div > form > div.modal-body > div > div > app-searchable-dropdown-field > div > div.form-group.ng-pristine.ng-invalid.ng-touched > div > span > ng-select > div > div > div.ng-input").setAttribute('aria-expanded', 'true');

Is there some other way to expand this list box so i can choose the options within?


Solution

  • If for whatever reason when you try clicking and it doesn't work what you can do is use page.type into that textbox location so you can trick the website into expanding the drop down box. Once that happens, the code you posted to find the selection in "countylocation" should work.

    Like this

    var countylocation = 'Cook County - Municipal Civil - District 2 - Skokie'
    
    await page.type(the_selector_here, countylocation);
    
    await page.waitFor(2000) //just in case
    
    await page.evaluate((countylocation) => {
        Array.from(document.querySelectorAll('span')).filter(li => {
            return li.innerText == countylocation
        }).forEach(element => {
            if (element) element.click(); // click on il with specific text
        });
    }, countylocation);
    

    Basically this will emulate as if a user is starting to type the location and then the drop box appears to show you the choice you're trying to make and then you click on it.