Braden Jageman
Braden Jageman

Reputation: 39

Selenium won't read the current input value

I'm running Selenium on a site that changes the value of a disabled input text box using jquery. Looking at the HTML, the value of the input box continues to say "Not Available" even though the value is obviously changed.

I can get the current value using Firebug with

$("#inputid").val() 

but I get the value "Not Available when I've used my selenium code:

driver.findElement(By.id("inputid")).getAttribute("value");

Any suggestions on how to get this value in Selenium? I want to avoid trying to use something like JavascriptExecutor but if that's the best solution it would be good to know.

I don't have access to the jQuery code so I can't help you there. Sorry :-/

Upvotes: 1

Views: 2161

Answers (1)

Louis
Louis

Reputation: 151441

If the value is changed by jQuery due to some DOM events, chances are your Selenium test is going to check for the new value too fast. You can get the value after it changes away from "Not Available" with something like this:

WebDriverWait wait = new WebDriverWait(driver,10);

String value = wait.until(new ExpectedCondition<String>() {
    public String apply(WebDriver driver) {
        String value = driver.findElement(By.id("inputid")).getAttribute("value");

        if value.equals("Not Available")
            return null;

        return value;
    }
});

(Disclaimer: It's been ages since I've written Java code so I may have goofed in the code above.) The wait.until call will run the apply method until it returns something else than null. It will wait for at most 10 seconds. The value returned by wait.until will be the value that was last returned by the apply that terminated the end. In other words, it will return the new value of the element.

You say

Looking at the HTML, the value of the input box continues to say "Not Available" even though the value is obviously changed.

Yes, that's a quirk of the DOM. When you change the value of the input field, the value attribute on the element that represent the input field does not change. What changes is the value property on the element. This is why you have to do $("#inputid").val(), not $("#inputid").attr('value').

Upvotes: 2

Related Questions