Question

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
Was it helpful?

Solution

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

OTHER TIPS

A simple work around could be using the value or the id attributed.

driver.findElement(By.id("optionRadio" + (option + 1))).click();

Also you can use xpath, something like this:

driver.findElement(By.xpath("//input[@value='1]")).click();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top