syntaxerror748
syntaxerror748

Reputation: 103

Puppeteer focus loop through input fields

I've got a page with 50 input fields that I'm trying to change the value of using Puppeteer.

Unfortunately just setting the value like below doesn't work since the website doesn't detect changes to the field:

await page.evaluate(() => {
    document.querySelectorAll('input[name="price"]').forEach(function(item) {
        item.value = "14,50";
    });
});

So I've discovered I have to use focus() and keyboard.type(). The problem I'm running into is that the input field don't have unique names and I don't know how to write a focus() selector that loops through the inputs.

<input _ngcontent-lhe-c73="" id="id" type="text" name="price" autocomplete="off" class="price-input" placeholder="vul de prijs in">
const inputs = await page.$eval('.price-input');
for (let i = 0; i < inputs.length; i++) {
    await page.evaluate(() => { document.querySelectorAll('input[name="price"]')[i].value = ''; });
    await page.focus('input[name="price"]['+i+']'); // this is invalid
    await page.keyboard.type('14,50');
}

How do I write a focus() selector to select the correct value in the loop? I've been trying with nth-child but this doesn't seem to be possible.

Upvotes: 4

Views: 774

Answers (1)

vsemozhebuty
vsemozhebuty

Reputation: 13812

You can try something like this:

const inputs = await page.$$('.price-input');
for (const input of inputs) {
    await page.evaluate((element) => { element.value = ''; }, input);
    await input.focus(); // May be redundant as we use the element for typing below.
    await input.type('14,50');
}

Upvotes: 1

Related Questions