21

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);
John Smith
  • 7,243
  • 6
  • 49
  • 61
karthikeya acharya
  • 243
  • 1
  • 3
  • 7

10 Answers10

38

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));
AutomatedOwl
  • 1,039
  • 1
  • 8
  • 14
  • 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. – Pedro García Medina May 03 '20 at 05:50
  • 1
    This solution does appear to work in the Python bindings too , but without the chords/actionchains sugar, and sending the DELETE key separately –  Dec 08 '20 at 17:18
  • 4
    For python, it's `from selenium.webdriver.common.keys import Keys; element.send_keys(Keys.CONTROL, "a"); element.send_keys(Keys.DELETE)` – AnT Dec 06 '21 at 03:09
  • looks like this does not work on mac since there we need `Keys.COMMAND` instead of `Keys.CONTROL` – fabb Mar 01 '23 at 10:37
  • this worked for me for a React app – netotz May 04 '23 at 20:51
16

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.

  • iamkenos
    • 1,446
    • 8
    • 24
    • 49
    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.

    Seggev
    • 91
    • 1
    • 5
    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);
    }
    
    mehpahgah
    • 31
    • 1
    3

    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);
                }
            }
    
        }
    
    Anver Sadhat
    • 3,074
    • 1
    • 25
    • 26
    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);
    
    John Smith
    • 7,243
    • 6
    • 49
    • 61
    Stepa_ua
    • 36
    • 1
    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");
    
    Norayr Sargsyan
    • 1,737
    • 1
    • 12
    • 26
    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.

    Martina K
    • 3
    • 4
    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);
    }
    
    NotMe
    • 3
    • 4
    -1
    javascriptExecutor js =(javascriptExecutor) driver;
    js.executescript("arguments[0].click()",webElement);
    
    jmoerdyk
    • 5,544
    • 7
    • 38
    • 49
    • 4
      Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) 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. – Yunnosch Apr 17 '23 at 10:47