Tuesday, February 19, 2013

[ Selenium 2.0 | WebDriver | Best practices ] Clear input element's value


Purpose

Clear value of HTML input element.
It should work successfully for browsers: Google Chrome, Firefox, IE, Safari.

Code sample


    protected void clearInput(WebElement webElement) {
        // isIE() - just checks is it IE or not - use your own implementation
        if (isIE() && "file".equals(webElement.getAttribute("type"))) {
            // workaround
            // if IE and input's type is file - do not try to clear it.
            // If you send:
            // - empty string - it will find file by empty path
            // - backspace char - it will process like a non-visible char
            // In both cases it will throw a bug.
            // 
            // Just replace it with new value when it is need to.
        } else {
            // if you have no StringUtils in project, check value still empty yet
            while (!StringUtils.isEmpty(webElement.getAttribute("value"))) {
                // "\u0008" - is backspace char
                webElement.sendKeys("\u0008");
            }
        }
    }


Notes

As for me, standard webElement.clear() doesn't work for all browsers. Commonly, it could not clear value and throws bug that element is not able to be clean:

Caused by: org.openqa.selenium.InvalidElementStateException: Element must not be hidden, disabled or read-only

No comments: