Entering Text Into Text Fields and Text Areas

Learn how you can interact with the text fields using Selenium, and try them out yourself.

Enter text into a text field by name

We can add text into a text field with the following command:

driver.findElement(By.name("username")).sendKeys("agileway");

Here, the name attribute is the identification used by the programmers to process data, and it applies to all the web controls in a standard web form.

In Selenium, we use sendKeys() function to send input from the keyboard or the mouse to the server.

Enter text into a text field by ID

We can do the same job by using IDs instead of names as well:

driver.findElement(By.id("user")).sendKeys("agileway");

Enter text into a password field

As we have discussed before, in Selenium, the password fields are treated as the normal text fields, except that the entered text is masked.

driver.findElement(By.id("pass")).sendKeys("testisfun");

Enter text into a multi-line text area

Selenium also treats text areas the same way as text fields.

driver.findElement(By.id("comments")).sendKeys("Automated testing is\r\nFun!");

Here, the \r\n represents a new line.

Get hands-on with 1200+ tech skills courses.