Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium WebDriver to select combo-box item?

We are using Selenium WebDriver and JBehave to run "integration" tests on our web-app. I have a method that will enter a value into a form input.

@When("I enter $elementId value $value")
public void enterElementText(final String elementId, final String value) {
    final WebElement webElement = webdriver.findElement(By.id(elementId));
    webElement.clear();
    webElement.sendKeys(value);
}

But when I try to use this to select an item in a drop-down list it (unsurprisingly) fails

java.lang.UnsupportedOperationException: You may only set the value of elements that are input elements

How do I select a value in the combo?

like image 668
Paul McKenzie Avatar asked Aug 03 '11 09:08

Paul McKenzie


People also ask

How do I select an item from a list in Selenium?

We can select an option from the dropdown list with Selenium webdriver. The Select class is used to handle static dropdown. A dropdown is identified with the <select> tag in an html code. Let us consider the below html code for <select> tag.

How do you select an element from a dropdown by using the value of an element to be selected?

Mastering XPath and CSS Selector for Selenium A dropdown is represented by <select> tag and the options are represented by <option> tag. To select an option with its value we have to use the selectByValue method and pass the value attribute of the option that we want to select as a parameter to that method.


1 Answers

This is how to do it:

@When("I select $elementId value $value")
public void selectComboValue(final String elementId, final String value) {
    final Select selectBox = new Select(web.findElement(By.id(elementId)));
    selectBox.selectByValue(value);
}
like image 111
Paul McKenzie Avatar answered Sep 21 '22 03:09

Paul McKenzie