Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set "value" to input web element using selenium?

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...

like image 665
Joe Avatar asked Feb 01 '16 09:02

Joe


People also ask

Can I set any of the attribute value of a WebElement in Selenium?

We can set any attribute value of a webelement in Selenium. Selenium can run Javascript commands by the executeScript method. The command to be executed is passed as an argument to the method.

How do I get the value of a web element?

The getAttribute() method helps to get the value of any attribute of a web element, which is returned as a String. If an attribute has a Boolean value, the method returns either True or null. Also, if there is no attribute, the method will return null.

How can you store a value in a text box in Selenium?

We can get the entered text from a textbox in Selenium webdriver. To obtain the value attribute of an element in the html document, we have to use the getAttribute() method. Then the value is passed as a parameter to the method. Let us consider a textbox where we entered some text and then want to get the entered text.


2 Answers

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 :)

like image 179
Shubham Jain Avatar answered Sep 17 '22 13:09

Shubham Jain


driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value"); 
like image 44
Kim Homann Avatar answered Sep 16 '22 13:09

Kim Homann