Select Radio Button in a group using Selenium WebDriver with Java
36,629
The code is absolutely working fine for me on Firefox 28. I have tried something like this:
function:
public void exampleInputRadio(WebDriver driver, int option) {
List<WebElement> radios = driver.findElements(By.name("exampleInputRadio"));
if (option > 0 && option <= radios.size()) {
radios.get(option - 1).click();
} else {
throw new NotFoundException("option " + option + " not found");
}
}
functions called:
TestClass tc = new TestClass();
tc.exampleInputRadio(driver, 1);
tc.exampleInputRadio(driver, 2);
tc.exampleInputRadio(driver, 3);
tc.exampleInputRadio(driver, 4);
Author by
Mass
Updated on November 16, 2020Comments
-
Mass over 3 years
I want to be able to select a radio button within a group (of radio buttons) identified by the name attribute:
<div> <input type="radio" name="exampleInputRadio" id="optionRadio1" value="1"> <input type="radio" name="exampleInputRadio" id="optionRadio2" value="2"> <input type="radio" name="exampleInputRadio" id="optionRadio3" value="3"> <input type="radio" name="exampleInputRadio" id="optionRadio4" value="4"> </div>
I use the following code to do what I want:
public void exampleInputRadio(WebDriver driver, int option) { List<WebElement> radios = driver.findElements(By.name("exampleInputRadio")); if (option > 0 && option <= radios.size()) { radios.get(option - 1).click(); } else { throw new NotFoundException("option " + option + " not found"); } }
The problem is that Selenium always selects the first radio button, no matter the value of
option
argument is.And when I code this in the above method:
for (int i = 0; i < radios.size(); i++) { System.out.println(radios.get(i).getAttribute("id")); }
I get this output:
optionRadio1 optionRadio2 optionRadio3 optionRadio4
-
Mass about 10 yearsThanks for the work around but I want to use the "name" attribute, and don't know why it does not work
-
bit about 10 yearsYou could use a xpath with the name as "exampleInputRadio" and id as "optionRadio" + (option+1)
-
byxor over 4 yearsAre you missing an apostrophe? e.g.
@value='1'