Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enter characters one by one in to a text field in selenium webdriver?

How to enter characters one by one in to a text field in selenium webdriver? I have used the below code but it's not working

getDriver().findElement(By.id("PhoneNumber")).sendKeys(Keys.chord("9876544322"));

Can anybody suggest how to resolve this?

like image 331
Rajendra Narayan Mahapatra Avatar asked Jun 30 '14 14:06

Rajendra Narayan Mahapatra


1 Answers

Here is how I am sending character by character using Selenium Webdriver (in Java). This way in the back-end, I verify at each letter press if the character exists in the input. Normal element.sendKeys() is not working well for me 2 out of 5 times - the last letter is missing, I guess something is buggy with Selenium Webdriver, I don't know. Try the code below, it works 100% of the time for me.

public void TypeInField(String xpath, String value){
    String val = value; 
    WebElement element = driver.findElement(By.xpath(xpath));
    element.clear();

    for (int i = 0; i < val.length(); i++){
        char c = val.charAt(i);
        String s = new StringBuilder().append(c).toString();
        element.sendKeys(s);
    }       
}

As you see, I get the value needed to be typed and in the for loop, I take each character, convert it to string and send it to textbox. Also, I have a search for xpath, you can change that to id, or classname, or whatever you want.

like image 108
Marțiș Paul Avatar answered Sep 29 '22 17:09

Marțiș Paul