0
0
Selenium Javatesting~5 mins

Clearing fields in Selenium Java

Choose your learning style9 modes available
Introduction

Clearing fields helps remove any existing text before typing new input. This avoids mistakes from leftover text.

When filling out a form that may have pre-filled or default text.
Before entering new data in a search box to avoid mixing old and new queries.
When testing input validation by clearing and entering different values.
To reset a field during automated test steps to ensure clean input.
When simulating user behavior of correcting or changing input.
Syntax
Selenium Java
WebElement element = driver.findElement(By.id("elementId"));
element.clear();

The clear() method removes all text from input or textarea fields.

It works only on elements that support text input.

Examples
Clear the username input field found by its name attribute.
Selenium Java
WebElement username = driver.findElement(By.name("username"));
username.clear();
Clear a search box using a CSS selector.
Selenium Java
WebElement searchBox = driver.findElement(By.cssSelector("input.search"));
searchBox.clear();
Clear a textarea field using an XPath locator.
Selenium Java
driver.findElement(By.xpath("//textarea[@id='comments']")).clear();
Sample Program

This test opens a login page, types an old email, clears the field, then types a new email. It checks if the new email is correctly set.

Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ClearFieldExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/login");

            WebElement emailField = driver.findElement(By.id("email"));
            emailField.sendKeys("oldemail@example.com");

            // Clear the field before entering new email
            emailField.clear();
            emailField.sendKeys("newemail@example.com");

            // Verify the field contains the new email
            String currentValue = emailField.getAttribute("value");
            if ("newemail@example.com".equals(currentValue)) {
                System.out.println("Test Passed: Field cleared and new text entered.");
            } else {
                System.out.println("Test Failed: Field value is incorrect.");
            }
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Always clear fields before typing if you want to avoid mixing old and new text.

Some fields may not support clear() if they are read-only or disabled.

Use meaningful locators to find the correct input fields reliably.

Summary

Clearing fields removes existing text before new input.

Use clear() on input or textarea elements.

Clearing helps tests avoid errors from leftover text.