i

Selenium Step By Step Guide

Handling Radio buttons and Checkboxes

Radio buttons and checkboxes are similar in the selection process; the only difference between these two is that Radio button options do not have multiple select capabilities, unlike checkboxes. Let us understand how we can handle both situations in our Selenium testing problem.

We need to locate the Radio button/Checkbox element to start further operations on it. I have used a webpage on http://www.echoecho.com/htmlforms10.htm for explaining this example.

 

Here the first step is to locate the radio button elements using any locator like id, name, className, and XPath, etc. Once we get a universal locator for one Radio button, then we can figure out all the Radio buttons in a list of elements. This tells us the total number of radio buttons present.

List elements=driver.findElements(By.xpath("//table[3]/tbody/tr/td/table/tbody/tr/td/input[@name='group2']"));

Let us figure out the total number of radio button present using the list of elements.

int iSize=elements.size();

Once we get the number of Radio buttons, then we can select the radio button easily by checking the Radio button’s value.

   for(int i=0;i

        {

               String btnValue=elements.get(i).getAttribute("value");

               if(btnValue.equalsIgnoreCase("Water"))

               {                    

                               elements.get(i).click();

               }

        }

Let us check the complete code to handle this situation below:

package SeleniumTest.SeleniumTest;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class RadioButtonCheckBox

{

    public static void main( String[] args )

    {

        System.setProperty("webdriver.chrome.driver","C:\\Users\\chromedriver.exe");

        WebDriver driver=new ChromeDriver();

        driver.get("http://www.echoecho.com/htmlforms10.htm");

        List elements=driver.findElements(By.xpath("//table[3]/tbody/tr/td/table/tbody/tr/td/input[@name='group2']"));

        int iSize=elements.size();

        System.out.println(iSize);

        for(int i=0;i

        {

               String btnValue=elements.get(i).getAttribute("value");

               if(btnValue.equalsIgnoreCase("Water"))

               {          

                               elements.get(i).click();     

               }

              

        }

        driver.quit();

    }

}