Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

I have an 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 Answers

0 votes
by (62.9k points)

Use findElement instead of findElements 

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

OR 

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

OR 

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

I hope this helps!

For further knowledge on Selenium, go for Selenium tutorial or Selenium training course by Intellipaat.

0 votes
by (1.1k points)
In Selenium, you can’t use .sendKeys() directly on an element like a hidden input since such fields are not visible in the DOM. Here use JavaScript instead to set the input  to a desired value.

Here is an approach to do that:

1. Locate the element.

2, Use Javascript to set the value.

The code to modify your hidden input’s value is given below:

// Locate the specific element

WebElement element = driver.findElement(By.xpath("//*[@id='invoice_supplier_id']"));

// Change the value using js

((JavascriptExecutor) driver).executeScript("arguments[0].value='desired_value';", element);

Change ‘desired_value’ to the value that one wants to set to the invoice_supplier_id.

This piece of code uses JavaScript to set the value property of the hidden input directly.

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...