MasterJoe
MasterJoe

Reputation: 2335

Why can't I clear an input field with javascript?

I want to clear & change the value of an input on the given url. The js I used does nothing and causes no errors. Why is this happening and how do I fix it ?

@Test
public void clearField() throws Exception {
    String url = "https://sfbay.craigslist.org/search/pen/apa?hasPic=1&search_distance=25&" +
            "postal=94014&nh=75&nh=80&min_price=1500&max_price=2500&bedrooms=1&bathrooms=1";
    //url = "https://sfbay.craigslist.org/search/pen/apa?housing_type=1";//Clear & set value works with this url.
    browser.get(url);

    WebElement element = browser.findElement(By.name("search_distance"));
    String char_sequence = "10";

    //Clear the field
    send_keys_v2(element, "");
    //Re write the field
    send_keys_v2(element, char_sequence);
}

public void send_keys_v1(WebElement element, String char_sequence) {
    ((JavascriptExecutor) browser).executeScript("arguments[0].value='" +
            char_sequence + "';", element);
}

public void send_keys_v2(WebElement element, String char_sequence) {
    ((JavascriptExecutor) browser).executeScript("arguments[0].setAttribute=('value', '" +
            char_sequence + "');", element);
}

References: Set value of input instead of sendKeys() - selenium webdriver nodejs

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

Upvotes: 2

Views: 2767

Answers (2)

lauda
lauda

Reputation: 4173

One possible and probable answer is that you have another element with the same name before the one that you are trying to clear.

Please inspect the html and check, if multiple elements found then the first one is taken.

As an alternative you can use a css selector like:

.searchInput[name*=search_distance]

Upvotes: 1

GibboK
GibboK

Reputation: 73928

Try to use in Selenium:

WebElement.clear()

void clear() If this element is a text entry element, this will clear the value. Has no effect on other elements. Text entry elements are INPUT and TEXTAREA elements. More info here.

Upvotes: 0

Related Questions