Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

SeleniumAutomation TestingTesting Tools

We can overwrite the value in the field instead of appending to it with sendKeys in Selenium webdriver. This can be done by using the Keys.chord method.It returns a string and can be applied to any web element with the help of the sendKeys method.

To overwrite a value, we shall first select it with CTRL+A keys and then pass the new value. Thus, Keys.CONTROL, A and the new value are passed as parameters to the Keys.chord method.

Syntax

String n = Keys.chord(Keys.CONTROL, "A");
WebElement l = driver.findElement(By.name("q"));
l.sendKeys(n, "Tutorialspoint");

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class OverWriteVals{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      //identify element
      WebElement m = driver.findElement(By.name("q"));
      m.sendKeys("Selenium");
      // Keys.chord to pass multiple strings
      String n = Keys.chord(Keys.CONTROL, "A");
      //overwrite value
      m.sendKeys(n, "Tutorialspoint");
      String s= m.getAttribute("value");
      System.out.println("Value after overwrite: " + s);
      driver.quit();
   }
}

Output

raja
Published on 07-Apr-2021 08:24:04
Advertisements