4

I am trying to validate an input like following

element.sendKeys(valueToPut);
String readAfterEnter = element.getText();

element.sendKeys(valueToPut) worked properly But readAfterEnter does not give the expected value, it is allways null.

LaurentG
  • 10,440
  • 8
  • 47
  • 64
Anis Haque
  • 41
  • 1
  • 2

2 Answers2

5

The WebElement.getText() method does not return the content of the user input. For this you have to use WebElement.getAttribute("value") (see this thread).

Community
  • 1
  • 1
LaurentG
  • 10,440
  • 8
  • 47
  • 64
3

This code will work:

WebElement element = driver.findElement(By.name("nameOfElement"));
String text = element.getAttribute("value");

The getAttribute method returns the value of an attribute of an HTML Tag; for example if I have an input like this:

<input name = "text" type ="text" value ="Hello">

then this webdriver code:

WebElement element = driver.findElement(By.name("text"));
String text = element.getAttribute("value");
System.out.println(text);

will print out 'Hello'.

Vince Bowdren
  • 7,115
  • 3
  • 27
  • 50
Abhishek Singh
  • 9,749
  • 20
  • 71
  • 102