How can I consistently remove the default text from an input element with Selenium? How can I consistently remove the default text from an input element with Selenium? selenium selenium

How can I consistently remove the default text from an input element with Selenium?


Okay, the script obviously kicks in when the clear() method clears the input and leaves it empty. The solutions it came up with are given below.

  1. The naïve one, presses Backspace 10 times:

    String b = Keys.BACK_SPACE.toString();searchField.sendKeys(b+b+b+b+b+b+b+b+b+b + username);

    (StringUtils.repeat() from Apache Commons Lang or Google Guava's Strings.repeat() may come in handy)

  2. The nicer one using Ctrl+A, Delete:

    String del = Keys.chord(Keys.CONTROL, "a") + Keys.DELETE; searchField.sendKeys(del + username);
  3. Deleting the content of the input via JavaScript:

    JavascriptExecutor js = (JavascriptExecutor)driver;js.executeScript("arguments[0].value = '';", searchField);searchField.sendKeys(username);
  4. Setting the value of the input via JavaScript altogether:

    JavascriptExecutor js = (JavascriptExecutor)driver;js.executeScript("arguments[0].value = '" + username + "';", searchField);

Note that javascript might not always work, as shown here: Why can't I clear an input field with javascript?


For what it is worth I'm have a very similar issue. WebDriver 2.28.0 and FireFox 18.0.1

I'm also using GWT but can reproduce it with simple HTML/JS:

<html><body><div><h3>Box one</h3><input id="boxOne" type="text" onfocus="if (this.value == 'foo') this.value = '';" onblur="if (this.value == '') this.value = 'foo';"/></div><div><h3>Box two</h3><input id="boxTwo" type="text" /></div></body></html>

This test fails most of the time:

@Testpublic void testTextFocusBlurDirect() throws Exception {  FirefoxDriver driver = new FirefoxDriver();  driver.navigate().to(getClass().getResource("/TestTextFocusBlur.html"));  for (int i = 0; i < 200; i++) {      String magic = "test" + System.currentTimeMillis();      driver.findElementById("boxOne").clear();      Thread.sleep(100);      driver.findElementById("boxOne").sendKeys(magic);      Thread.sleep(100);      driver.findElementById("boxTwo").clear();      Thread.sleep(100);      driver.findElementById("boxTwo").sendKeys("" + i);      Thread.sleep(100);      assertEquals(magic, driver.findElementById("boxOne").getAttribute("value"));  }  driver.quit();}

It could just be the OS taking focus away from the browser in a way WebDriver can't control. We don't seem to get this issue on the CI server to maybe that is the case.


I cannot add a comment yet, so I am putting it as an answer here. I want to inform you that if you want to use only javascript to clear and/or edit an input text field, then the javascript approach given by @slanec will not work. Here is an example: Why can't I clear an input field with javascript?