How to input text in the text box without calling the sendKeys() using Selenium?

We can input text in the text box without the method sendKeys with thehelp of the JavaScript Executor. Selenium executes JavaScript commands with the help of the executeScript method.

The JavaScript command to be run is passed as parameter to the method. To enter text we shall first identify the input box with the JavaScript method document.getElementById. Then we have to apply the value method on it.

Let us enter text Selenium in the below input box −


JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript ("document.getElementById('gsc-i-id1').value='Selenium'");


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JsEnterText{
   public static void main(String[] args) {
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      // JavaScript Executor to enter text
      JavascriptExecutor j = (JavascriptExecutor)driver;
      j.executeScript ("document.getElementById('gsc-i-id1').value='Selenium'");
      WebElement l = driver.findElement("gsc-i-id1"));
      String s = l.getAttribute("value");
      System.out.println("Value entered is: " + s);


Updated on: 03-Apr-2021

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started