Ways to Clear/Fill the Input field with Selenium

Selenium clear input different waysSelenium provides a standard way of working with input elements which is described below. But there are also cases when it’s not working properly. So there are another solution.

So, let’s check it out.

The standard way of filling inputs in Selenium library

It’s done it 2 steps:

  • clear the field using method clear(). This step is needed to prevent cases, when input is already populated.
  • fill it using method sendKeys(CharSequence… keysToSend)

Example:

driver.findElement(By.xpath("SOME XPATH EXPRESSION")).clear();
driver.findElement(By.xpath("SOME XPATH EXPRESSION")).sendKeys("test value");

Another approach for clearing input

I faced a case, when the UI written with React.js didn’t work properly with the clear() method. The value was cleared, but the input component did not save the change.

So, the other way for clearing field is passing the hotkeys to a field:

driver.findElement(By.xpath("SOME XPATH EXPRESSION")).clear();
driver.findElement(By.xpath("SOME XPATH EXPRESSION")).sendKeys("test value");

As you can see, I just send hot keys Ctrl+A and Del to emulate the different behavior for removing input content. You can also the static method Keys.chord for key sequences: sendKeys(Keys.chord(Keys.CONTROL, “a”).

NOTE for Mac users: probably, replace Keys.CONTROL with Keys.COMMAND.

You can also send the BackSpace code repeatedly:

for (int i = 0, i < 10, i++) {
    driver.findElement(By.xpath("SOME XPATH EXPRESSION")).sendKeys(Keys.BACK_SPACE);
}

If it don’t work for you, leave a comment, and maybe I will be able to help you.

Leave a Reply

Be the First to Comment!