Playwright prefers locators over Puppeteer-style $
and eval
methods. With locator
, you can use inputValue
to get the current input value for one or more elements.
You can also call page.inputValue(selector)
directly to get the input value of the first matching selector, but that's now discouraged in favor of the locator approach.
Here's a couple of minimal, complete examples:
const playwright = require("playwright"); // ^1.30.0
let browser;
(async () => {
browser = await playwright.chromium.launch();
const page = await browser.newPage();
await page.setContent(`<input value="foo">`);
console.log(await page.inputValue("input")); // => foo
const input = page.locator("input");
await input.fill("bar");
console.log(await input.inputValue()); // => bar
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
If you have multiple elements:
const playwright = require("playwright");
const html = `<input value="foo"><input value="bar">`;
let browser;
(async () => {
browser = await playwright.chromium.launch();
const page = await browser.newPage();
await page.setContent(html);
console.log(await page.inputValue("input")); // => foo
const loc = page.locator("input");
await loc.nth(1).fill("baz");
// iterate all:
for (const el of await loc.all()) {
console.log(await el.inputValue());
}
// or make an array (option 1):
const values1 = await Promise.all(
[...await loc.all()].map(e => e.inputValue())
);
console.log(values1); // => [ 'foo', 'baz' ]
// or make an array (option 2):
const values2 = await loc.evaluateAll(els => els.map(el => el.value));
console.log(values2); // => [ 'foo', 'baz' ]
})()
.catch(err => console.error(err))
.finally(() => browser?.close());