Want to clear all inputs in a form quickly?

Dheeraj Gambhir
1 min readFeb 16, 2022

--

While submitting a form, at times, we get a use case where we need to first clear the default/pre-filled values of all the fields in the form and then enter our desired value.

In that case we usually do this for every field in that form:

WebElement firstName = driver.findElement(By.id(“Form_submitForm_FullName”));

email.clear();

email.sendKeys(“Dheeraj”);

So, here we are locating an element, assigning it to a WebElement. After that, we send commands:

> clear() to clear the value into the input field

> And then the sendKeys() to fill it in with a new desired value.

But isn’t it time-consuming to find all the fields in the form and then clear each field 1 by 1?

Here is the faster alternative…

You can send a Javascript command to clear all the fields at one shot:

document.getElementById(‘Form_submitForm’).reset()

This is just an alternative to reduce some test execution time. You can use any approach that works best for you.

Here is the working example:

public class Form {

WebDriver driver;

@Test

private void testClearForm() throws InterruptedException {

WebDriverManager.chromedriver().setup();

ChromeOptions options = new ChromeOptions();

options.addArguments(“start-maximized”);

driver = new ChromeDriver(options);

driver.get(“https://www.orangehrm.com/contact-sales/");

driver.findElement(By.id(“Form_submitForm_FullName”)).sendKeys(“Dheeraj”);

driver.findElement(By.id(“Form_submitForm_CompanyName”)).sendKeys(“TestCompany”);

driver.findElement(By.id(“Form_submitForm_JobTitle”)).sendKeys(“TestQA”);

Select drpNoOfEmployees = new Select(driver.findElement(By.name(“NoOfEmployees”)));

drpNoOfEmployees.selectByVisibleText(“16–20”);

driver.findElement(By.id(“Form_submitForm_Contact”)).sendKeys(“9090909090”);

driver.findElement(By.id(“Form_submitForm_Email”)).sendKeys(“test@dg.com”);

driver.findElement(By.id(“Form_submitForm_Comment”)).sendKeys(“Test Comments”);

Thread.sleep(4000);

((JavascriptExecutor) driver).executeScript(“document.getElementById(‘Form_submitForm’).reset()”);

}

}

--

--

No responses yet