Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

        searchField.click();
        if(!searchField.getAttribute("value").isEmpty()) {
            // clear field, if not already empty 
            searchField.clear();
        }
        if(!searchField.getAttribute("value").isEmpty()) {
            // if it still didn't clear, click away and click back
            externalLinksHeader.click();
            searchField.click();
        }

        searchField.sendKeys(username);

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 setDefaultText() gets called both onBlur() and onChange() if the change results in an empty text field. Guess that's why the searchField.clear() 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.

like image 324
mcole Avatar asked Jun 28 '12 19:06

mcole


1 Answers

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?

like image 142
Petr Janeček Avatar answered Oct 04 '22 19:10

Petr Janeček