How to set “value” to input web element using selenium?

SeleniumAutomation TestingTesting Tools

We can set value to input webelement using Selenium webdriver. We can take the help of the sendKeys method to enter text to the input field. The value to be entered is passed as an argument to the method.

Syntax

driver.findElement(By.id("txtSearchText")).sendKeys("Selenium");

We can also perform web operations like entering text to the edit box with Javascript Executor in Selenium. We shall use the executeScript method and pass argument index.value='<value to be entered>' and webelement as arguments to the method.

Syntax

WebElement i = driver.findElement(By.id("id"));
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("arguments[0].value='Selenium';", i);

Example

Code Implementation

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
public class SetValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
      l.sendKeys("Selenium");
      // obtain the value entered with getAttribute method
      System.out.println("Value entered is: " +l.getAttribute("value"));
      driver.close();
   }
}

Example

Code Implementation with Javascript Executor.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class SetValueJS{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
      // Javascript Executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor)driver;
      j.executeScript("arguments[0].value='Selenium';", l);
      System.out.println("Value entered is: " +l.getAttribute("value"));
      driver.close();
   }
}

Output

raja
Published on 26-Oct-2020 11:38:10
Advertisements