selenium clear() command doesn't clear the element
Asked Answered
N

13

22

I have been writing selenium scripts for a while in Java. I encountered a very weird issue today. Here is the issue:

I cleared a text field using webelement.clear() method, later while executing next command (click event), the text area I had previously cleared, is now populated with previously filled value.

Here is the code snippet:

mobileNumField.get(0).clear();
Thread.sleep(4500);
emailAddress.get(0).click();
emailAddress.get(0).clear();
Thread.sleep(4500);
emailAddress.get(0).sendKeys(Keys.TAB);
Nightcap answered 4/6, 2018 at 9:49 Comment(0)
S
1

Faced a similar problem. The input field is cleared but the error message is not updated. It seems that some input fields work correctly only if you enter and delete a character:

element.sendKeys(text);
element.sendKeys(Keys.SPACE, Keys.BACK_SPACE);
Shandashandee answered 24/2, 2020 at 1:0 Comment(0)
E
43

I don't know the exact reason for your element keeping its value, but you can try an alternative text clearance by sending 'Ctrl+A+Delete' key combination using sendKeys method of the element's object:

emailAddress.sendKeys(Keys.chord(Keys.CONTROL,"a", Keys.DELETE));
Etruscan answered 4/6, 2018 at 13:49 Comment(6)
As a complement to this solution: if the input field has text with special characters (for example, an input for a date that has '/') the sending of those keys must be break in two steps. First CONTROL + a, and then DELETE; otherwise, just a segment, until the first special character, of the text is deleted.Shiism
This solution does appear to work in the Python bindings too , but without the chords/actionchains sugar, and sending the DELETE key separatelyCommunicate
For python, it's from selenium.webdriver.common.keys import Keys; element.send_keys(Keys.CONTROL, "a"); element.send_keys(Keys.DELETE)Ostiary
looks like this does not work on mac since there we need Keys.COMMAND instead of Keys.CONTROLAnastice
this worked for me for a React appTriad
I would follow AnT's suggestion and send the CONTROL-a separate from the DELETE. Doing all three together as a chord may work, but I think that would be a bit flaky since it would depend on whether the "A" happened before the "DELETE".Pamphlet
T
17

It's possible that the fields you're trying to fill has autocomplete attribute set to on. [Reference]

If clear() works when the line executes then it's safe to say that this is not a webdriver specific issue.

It would help if you can show the html snippet of the page section you're working on.

Possible areas of debugging:

  • forcefully remove autocomplete attribute on page load using java script executor
  • turn off autocomplete setting on the driver level. I believe the solution would vary depending on the driver being used.

    Good luck!

    PS: Those Thread.sleep(s) are not advisable.

  • Thun answered 5/6, 2018 at 3:38 Comment(2)
    Though not a direct solution, this was a good explanation. Mine had autocomplete.Stilted
    Best explanation, saved my dayMerge
    M
    9

    I solved it by adding a function to my BasePage to clear fields by a given WebElement.

     public void clearWebField(WebElement element){
        while(!element.getAttribute("value").equals("")){
            element.sendKeys(Keys.BACK_SPACE);
        }
    }
    

    You can also implement this method in the page that experiencing the problem.

    Millionaire answered 2/9, 2020 at 15:11 Comment(0)
    O
    4

    I am using Mac and the following code helps also

      public static void macCleanHack(WebElement element) {
            String inputText = element.getAttribute("value");
            if( inputText != null ) {
                for(int i=0; i<inputText.length();i++) {
                    element.sendKeys(Keys.BACK_SPACE);
                }
            }
    
        }
    
    Outstare answered 25/9, 2020 at 16:1 Comment(0)
    T
    3

    I had a similar issue with a text field that used an auto-complete plugin. I had to explicitly clear the attribute value as well as do a SendKeys. I created an extension method to encapsulate the behaviour, hopefully the snippet below will help:

    public static void SendKeysAutocomplete(this IWebElement element, string fieldValue)
    {
       element.SendKeys(fieldValue);
       element.SetAttribute("value", fieldValue);
    }
    
    public static void SetAttribute(this IWebElement element, string attributeName, string attributeValue)
    {
       var driver = WebDriverHelper.GetDriverFromScenarioContext();
    
       var executor = (IJavaScriptExecutor)driver;
       executor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, attributeName, attributeValue);
    }
    
    Troudeloup answered 27/3, 2019 at 9:56 Comment(0)
    S
    1

    Faced a similar problem. The input field is cleared but the error message is not updated. It seems that some input fields work correctly only if you enter and delete a character:

    element.sendKeys(text);
    element.sendKeys(Keys.SPACE, Keys.BACK_SPACE);
    
    Shandashandee answered 24/2, 2020 at 1:0 Comment(0)
    T
    1

    Clear() didn't work for me either. This method I wrote is working for me as of 2024

    public void ClearText(By element)
        {
            IWebElement elementToClear = driver.FindElement(element);
            elementToClear.Click();
            Actions actions = new Actions(driver);
            actions.KeyDown(Keys.Control).SendKeys("a").KeyUp(Keys.Control);
            actions.Perform();
            actions.SendKeys(Keys.Delete);
            actions.Perform();
        }
    
    Timofei answered 10/1 at 14:41 Comment(0)
    E
    0

    Hope this helps to clear the field and then sendKeys() the needed value

     while (!inputField.getAttribute("value").equals("")) {
            inputField.sendKeys(Keys.BACK_SPACE);
           }
            inputField.sendKeys("your_value");
    
    Everest answered 1/12, 2020 at 7:10 Comment(0)
    F
    0

    In some webforms clearing the field followed by .sendKeys() won't work because it keeps repopulating it with some autofill value (in my case it was due to an onfocus attribute function of an input element). Action chains didn't help, the only thing that worked for me was replacing the value attribute directly with javascript:

    In Java:

    driver.executeScript("document.getElementById('elementID').value='new value'");
    

    In Python (nearly identical):

    driver.execute_script("document.getElementById('elementID').value='new value'")
    

    For more on the Java version of this solution see this question.

    Fabyola answered 28/10, 2022 at 11:51 Comment(0)
    L
    0

    Faced something similiar. I had required inputs field and when they were cleared, they would not update the verification. What I did was to create custom method that would check if the element.Text is empty and then it would send Keys.LeftControl + "a" + Keys.Delete

    public static void Clear(WindowsElement element)
    {
        if (element.Text != String.Empty)
            element.SendKeys(Keys.LeftControl + "a" + Keys.Delete);
    }
    
    Loriannlorianna answered 27/2, 2023 at 16:9 Comment(0)
    T
    0

    Thanks @agleno I've reused your code and it was very helpful. Also, it can be written like this, because I have coded it for cross OS/browser combinations.

    For me it helped to send .clear() command twice. Hope it will be helpful to others:

    public static Actions getBrowserActions() {
      return new Actions(driver);
    }
    
    /*
    WebDriver has problem to clear input field when they contain 
    'autocomplete' attribute. This method is workaround to clear these input 
    fields. 
    'role' == 'search' condition is workaround for input fields 
    where 'autocomplete' will manifest with drop-down context-menu. Other 
    input fields will be cleared with double '.clear()' call.
    
    If your field with search autocomplete does not has 'role' attribute
    please find some other attribute that will be different than classic 
    input fields.
    */
    public static void clearInputWebElement(final WebElement webElement) {
      if (webElement.getAttribute("role") != null) {
       if (webElement.getAttribute("role").equals("search")) {
        webElement.click();
        if (SystemUtils.IS_OS_MAC) {
        // MacOS has Command key
          getBrowserActions()
            .keyDown(Keys.COMMAND)
            .sendKeys("A")
            .keyUp(Keys.COMMAND)
            .sendKeys(Keys.BACK_SPACE)
            .build()
            .perform();
        } else {
        // Windows and Ubuntu has Control key
          getBrowserActions()
            .keyDown(Keys.CONTROL)
            .sendKeys("A")
            .keyUp(Keys.CONTROL)
            .sendKeys(Keys.BACK_SPACE)
            .build()
            .perform();
        }
       }
      } else {
        webElement.clear();
        webElement.clear();
      }
    }
    
    Tressa answered 10/1 at 15:33 Comment(0)
    I
    0

    I using Java 17 and Selenium, and this code worked for me.

    Actions actions = new Actions(DriverManager.getWebDriver());
    
    actions.moveToElement(webElement).doubleClick().click().sendKeys(Keys.BACK_SPACE).perform();
    
    Improve answered 16/7 at 11:50 Comment(0)
    C
    -1
    javascriptExecutor js =(javascriptExecutor) driver;
    js.executescript("arguments[0].click()",webElement);
    
    Culpepper answered 16/4, 2023 at 14:50 Comment(1)
    Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Cyanide

    © 2022 - 2024 — McMap. All rights reserved.