'In Selenium Webdriver using Java should I have to use element.click() before element.SendKeys for input text box?

driver.get("<url>")
WebElement name = driver.findElement(By.id(..));
name.click();
name.sendKeys("<input text>");

In the above code is it required to have name.click() first , or is it optional as the field is located and it should be able to send the input without having to click on it first



Solution 1:[1]

<input> tag

The <input> tag specifies an input field where the user can enter data. The <input> element can be displayed in different ways, depending on the type attribute. As an example:

  • <input type="text"> (default value)
  • <input type="button">
  • <input type="checkbox">
  • <input type="email">
  • <input type="file">
  • <input type="hidden">
  • <input type="number">
  • <input type="password">
  • <input type="radio">
  • <input type="submit">
  • <input type="url">

This usecase

As your usecase involves sending a character sequence presumably it should be of the following type:

<input type="text">

Generally you won't have to invoke click() before invoking sendKeys() but ideally to send a character sequence you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("birtviewer"))).sendKeys("Richard Bernard");
  

However, incase the element is a dynamic element having onfocus event attribute which fires the moment that the element gets focus as follows:

<input type="text" id="fname" onfocus="myFunction(this.id)">

you may require the additional step to click within the element.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1