mcole mcole - 1 year ago 118
Java Question

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

I'm trying to use Selenium WebDriver to input text to a GWT input element that has default text, "Enter User ID". Here are a few ways I've tried to get this to work:;
if(!searchField.getAttribute("value").isEmpty()) {
// clear field, if not already empty
if(!searchField.getAttribute("value").isEmpty()) {
// if it still didn't clear, click away and click back;;


The strange thing is the above this only works some of the time. Sometimes, it ends up searching for "Enter User IDus", basically beginning to type "username" after the default text -- and not even finishing that.

Any other better, more reliable ways to clear out default text from a GWT element?

Edited to add: The HTML of the input element. Unfortunately, there's not much to see, thanks to the JS/GWT hotness. Here's the field when it's unselected:

<input type="text" class="gwt-TextBox empty" maxlength="40">

After I've clicked it and given it focus manually, the default text and the "empty" class are removed.

The JS to
gets called both
if the change results in an empty text field. Guess that's why the
isn't helping.

I've also stepped through this method in debug mode, and in that case, it never works. When run normally, it works the majority of the time. I can't say why, though.

Answer Source

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

  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);
  4. Setting the value of the input via JavaScript altogether:

    JavascriptExecutor js = (JavascriptExecutor)driver;
    js.executeScript("arguments[0].value = '" + username + "';", searchField);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download