How to delete default values in text field using Selenium?


We can delete default values in the text field with Selenium webdriver. There are multiple ways to do this. We can use the clear() method which resets value present already in edit box or text area field.

We can use the Keys.chord() method along with sendKeys(). The Keys.chord() method helps to press multiple keys simultaneously. It accepts the sequence of keys or strings as a parameter to the method.

To delete default values, it takes, Keys.CONTROL, "a" as parameters. This string is then sent as a parameter to the sendKeys() method. Finally, we have to pass Keys.DELETE to the sendKeys() method.

Let us consider the below edit field where we will delete the input values.

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;

public class DelDefaultVal{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // input text
      l.sendKeys("Selenium");
      // delete default value with clear()
      l.clear();
      driver.quit()
   }
}

Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class DelDefaultValue{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // input text
      l.sendKeys("Selenium");
      // sending Ctrl+a by Keys.Chord()
      String s = Keys.chord(Keys.CONTROL, "a");
      l.sendKeys(s);
      // sending DELETE key
      l.sendKeys(Keys.DELETE);
      driver.quit()
   }
}

Updated on: 18-Sep-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements