I’m working on automated testing and need to modify text in an input field that already has content. The field shows data from a database record that I want to replace with new test data.
When I use await page.type('#textField', 'new content'); it just adds the text to what’s already there instead of replacing it. I need a way to clear out the existing content first.
// Current approach only appends text
await page.type('#textField', 'updated value');
// Results in: "original textupdate value"
What’s the best method to completely replace the existing text in an input element rather than just adding to it?
try selecting all the text first, then type over it. await page.focus('#textField'); await page.keyboard.down('Control'); await page.keyboard.press('KeyA'); await page.keyboard.up('Control'); await page.type('#textField', 'new text'); works well for me - it’s basically what users do.
I’ve had good luck using page.click() with multiple clicks to select everything before typing. Try await page.click('#textField', { clickCount: 3 }); then your type command. Triple-click grabs all the text, and typing just overwrites it. This works great with React components where direct DOM manipulation gets overridden by state management. It feels like natural user behavior and works consistently across different input types - no need to mess with keyboard combos or evaluate scripts.
Had this same problem testing forms with pre-filled data. Triple-click works most of the time, but I’ve had better luck using page.evaluate() to set the value directly - it’s way more reliable across different inputs and browsers.
This skips all the selection headaches and guarantees the field’s empty before you start typing. Been using this in production test suites for ages - handles weird edge cases much better than keyboard tricks, especially with custom form components.