56

I have element in my code that looks like this:

<input id="invoice_supplier_id" name="invoice[supplier_id]" type="hidden" value="">

I want to set its value, so I created a web element with it's xpath:

 val test = driver.findElements(By.xpath("""//*[@id="invoice_supplier_id"]"""))

but now I dont see an option to set the value...

2
  • 1
    If you're working with an ID, you should use the appropriate By-Locator: By.id("invoice_supplier_id") Commented Feb 1, 2016 at 9:54
  • 1
    You are currently collecting a list of WebElements. You will need to extract the WebElement from the list, or just find the WebElement by itself. You will also need to unhide the element before Selenium can interact with it. Commented Feb 1, 2016 at 10:31

3 Answers 3

76

Use findElement instead of findElements

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");

OR

driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");

**OR using JavascriptExecutor **

WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
 JavascriptExecutor jse = (JavascriptExecutor)driver;
 jse.executeScript("arguments[0].value='enter the value here';", element);

OR

(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);

OR (in javascript)

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")

Hope it will help you :)

Sign up to request clarification or add additional context in comments.

7 Comments

Send keys to a hidden element?
I am getting same problem here. But there is no such setAttribute method in WebElement. Any other suggestion ?
@NarayanSubedi, the sendKeys method is working to me driver.findElement(By.id("elementId")).sendKeys("value", "new value");
try using send_keys in place of sendKeys
Anyone having problems with this method can try sqa.stackexchange.com/questions/3387/…
|
4
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");

EDIT: Obviously, the setAttribute() method is not available any more for objects of type WebElement. No idea how to solve this.

3 Comments

findElement() returns a WebElement. WebElement does not have a setAttribute() method.
@Nathan, how about element.__setattr____("value", "your value")?
There is not setAttribute method available.
2

As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"‌​, "new value");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.