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);
Share:
36,629
Mass
Author by

Mass

Updated on November 16, 2020

Comments

  • Mass
    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
    Mass about 10 years
    Thanks for the work around but I want to use the "name" attribute, and don't know why it does not work
  • bit
    bit about 10 years
    You could use a xpath with the name as "exampleInputRadio" and id as "optionRadio" + (option+1)
  • byxor
    byxor over 4 years
    Are you missing an apostrophe? e.g. @value='1'