Handling radio buttons in Selenium WebDriver with Java

In this post, we will see how to handle radio buttons on webpage using Selenium WebDriver with Java.

We can get the list of radio buttons, get the status of those, select any of the radio buttons using WebDriver.

Radio button is like a normal WebElement, so we can apply any of the WebElement’s methods to radio button element.

Get the list of radio buttons :

List<WebElement> browserRadios = driver.findElements(By.name(“group1”));

Get the total number of radio buttons :

System.out.println(“Total no of radio buttons ” + browserRadio.size());

Get a particular radio button by INDEX :

WebElement firstRadioButton = browserRadios.get(0);

WebElement secondRadioButton = browserRadios.get(1);

Get a particular radio button by VALUE :

WebElement butterRadioButton;

for (int i = 0; i < browserRadio.size(); i++) {

            if (browserRadio.get(i).getAttribute(“value”).equalsIgnoreCase(“butter”)) {
                  butterRadioButton = browserRadio.get(i);

                   break;
            }

}

Check the status of the Radio button (whether it is selected or not) :

System.out.println(“Radio button is selected” + butterRadioButton.isSelected());

Select the Radio button :

System.out.println(“Selecting 2nd radio button”);

browserRadios.get(1).click());

 

Let’s have a look at the code snippet, performing multiple operations on radio buttons.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumFirstScript {
             public static void main(String[] args) {
             WebDriver driver = new FirefoxDriver();
             driver.manage().window().maximize();
             driver.get(“http://www.echoecho.com/htmlforms10.htm”);

             List<WebElement> browserRadio = driver.findElements(By.name(“group1”));
             System.out.println(“Total no of radio buttons ” + browserRadio.size());

             for (int i = 0; i < browserRadio.size(); i++) {

                      if (browserRadio.get(i).getAttribute(“value”).equalsIgnoreCase(“butter”)) {
                                 browserRadio.get(i).click();
                     }

                      System.out.println(browserRadio.get(i).getAttribute(“value”)
                      + ” radio button is checked: “
                      + browserRadio.get(i).isSelected());
              }

             driver.quit();
       }
}

Hope it helps you !!

Cheers 🙂

 

Advertisements

#get-status-of-radio-button, #get-the-list-of-radio-buttons, #handling-radio-buttons-in-webdriver