85

In WebDriver, if I use sendKeys it will append my string to the value that already exists in the field. I can't clear it by using clear() method because the second I do that, the webpage will throw an error saying that it has to be between 10 and 100. So I can't clear it or an error will be thrown before I can put in the new value using sendKeys, and if I sendKeys it just appends it to the value already there.

Is there anything in WebDriver that lets you overwrite the value in the field?

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
True_Blue
  • 1,387
  • 2
  • 10
  • 13

12 Answers12

122

You can also clear the field before sending it keys.

element.clear()
element.sendKeys("Some text here")
Tim Banks
  • 7,099
  • 5
  • 31
  • 28
  • 9
    True_Blue mentioned in the question that he can't use clear() because the second he does that, the webpage will throw an error saying that it has to be between 10 and 100. – Jan Hrcek Mar 08 '13 at 13:06
  • 5
    Good call. I will keep my answer here just in case it is some use to someone in the future since the title doesn't specify that. – Tim Banks Mar 08 '13 at 20:07
  • 6
    Additional info if this solution doesn't work for someone: make sure that `element.GetAttribute("value")` really has a value before calling `element.clear()` (wait for this value to be non empty). It sometimes happens when testing AngularJS inputs with ngModel directive. – Łukasz Wiatrak Apr 26 '15 at 17:32
  • Worked for me, even if empty field. – Chris Ciszak May 09 '17 at 10:36
  • Worked for me too on empty fields. – MiB Dec 06 '22 at 07:17
102

I think you can try to firstly select all the text in the field and then send the new sequence:

from selenium.webdriver.common.keys import Keys
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
EndermanAPM
  • 327
  • 2
  • 22
Sergii Pozharov
  • 17,366
  • 4
  • 29
  • 30
  • 2
    Yeah that worked, I just had to import the Keys class in. Thank you very much. – True_Blue Jul 15 '10 at 15:51
  • I am trying it in Pyton. How do I import `Keys`? – Volatil3 Nov 14 '14 at 19:56
  • @scarba05 It is possible that your Linux Desktop uses different command to select all text instead of Ctrl+A, however in most cases it should work – Sergii Pozharov Jan 12 '15 at 13:10
  • It was being run through a Jenkins server job, not on the desktop. Centos 5 Linux environment I think (I can't check as I'm no longer working with that client). – scarba05 Feb 25 '15 at 16:40
  • 2
    @BaoNgo For Macs, you need to use `Keys.COMMAND` instead of `Keys.CONTROL`. – MForMarlon Sep 24 '15 at 19:08
  • 3
    @SergiiPozharov Is there a Python equivalent to this command? I have used `send_keys` but I get an error `AttributeError: type object 'Keys' has no attribute 'chord'` – James Hayek Jul 21 '19 at 23:49
  • 4
    Found it. `element.send_keys(Keys.CONTROL, 'a')` – James Hayek Jul 21 '19 at 23:53
  • As @BaoNgo pointed out: That's not platform independent. Is there no better option? – Martin Apr 07 '20 at 08:35
  • Generally you should use element.clear() because situation described in the question does not seem to be a correct implementation. If you have to deal with inability to clear the element, you can either detect the platform in your test code and use appropriate combination or try something like calling Javascript to do "triple click", but I am not sure if it is possible and is platform independent – Sergii Pozharov Apr 08 '20 at 21:41
23

Okay, it is a few days ago... In my current case, the answer from ZloiAdun does not work for me, but brings me very close to my solution...

Instead of:

element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");

the following code makes me happy:

element.sendKeys(Keys.HOME, Keys.chord(Keys.SHIFT, Keys.END), "55");

So I hope that helps somebody!

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
ChangeRequest
  • 532
  • 4
  • 12
  • I used this -> element.sendKeys(Keys.HOME,Keys.chord(Keys.SHIFT, Keys.ARROW_DOWN, Keys.ARROW_DOWN, Keys.ARROW_DOWN)); This was amazing it selects 3 lines of text in a textarea box because Command A didnt work for me either – mishmaccas Dec 08 '15 at 23:45
9

In case it helps anyone, the C# equivalent of ZloiAdun's answer is:

element.SendKeys(Keys.Control + "a");
element.SendKeys("55");
Noah Heldman
  • 6,724
  • 3
  • 40
  • 40
8

This worked for me.

mElement.sendKeys(Keys.HOME,Keys.chord(Keys.SHIFT,Keys.END),MY_VALUE);
Ajinkya
  • 22,324
  • 33
  • 110
  • 161
Guy Engel
  • 2,436
  • 1
  • 17
  • 13
2

Use this one, it is trusted solution and works well for all browsers:

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");
        }
    }
}

If input has type="file" - do not clear it for IE. It will try to find file by empty path and will throw a bug.

More details you could find on my blog

Gadget
  • 474
  • 1
  • 5
  • 12
  • Sorry, I understood it wrong. My solution - is only about right way to clear input value, but not about how to replace current value with new one in one action – Gadget Feb 20 '13 at 16:28
2

Had issues using most of the mentioned methods since textfield had not accepted keyboard input, and the mouse solution seem not complete.

This worked for to simulate a click in the field, selecting the content and replacing it with new.

     Actions actionList = new Actions(driver);
     actionList.clickAndHold(WebElement).sendKeys(newTextFieldString).
     release().build().perform();
1

Use the following:

driver.findElement(By.id("id")).sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.DELETE), "Your Value");
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Akhil
  • 21
  • 5
0

This solved my problem when I had to deal with HTML page with embedded JavaScript

WebElement empSalary =  driver.findElement(By.xpath(PayComponentAmount));
Actions mouse2 = new Actions(driver);
mouse2.clickAndHold(empSalary).sendKeys(Keys.chord(Keys.CONTROL, "a"), "1234").build().perform();

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].onchange()", empSalary);
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Prasanth RJ
  • 137
  • 1
  • 8
0

The original question says clear() cannot be used. This does not apply to that situation. I'm adding my working example here as this SO post was one of the first Google results for clearing an input before entering a value.

For input where here is no additional restriction I'm including a browser agnostic method for Selenium using NodeJS. This snippet is part of a common library I import with var test = require( 'common' ); in my test scripts. It is for a standard node module.exports definition.

when_id_exists_type : function( id, value ) {
driver.wait( webdriver.until.elementLocated( webdriver.By.id( id ) ) , 3000 )
    .then( function() {
        var el = driver.findElement( webdriver.By.id( id ) );
        el.click();
        el.clear();
        el.sendKeys( value );
    });
},

Find the element, click it, clear it, then send the keys.

This page has a complete code sample and article that may help.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Lance Cleveland
  • 3,098
  • 1
  • 33
  • 36
0

This is something easy to do and it worked for me:

//Create a Javascript executor

JavascriptExecutor jst= (JavascriptExecutor) driver;
jst.executeScript("arguments[1].value = arguments[0]; ", 55, driver.findElement(By.id("id")));

55 = value assigned

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
nosequeweaponer
  • 511
  • 10
  • 38
0
 WebElement p= driver.findElement(By.id("your id name"));
 p.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Jan 25 '21 at 07:08