How To Select Radio Buttons In Selenium WebDriver?

This Tutorial Explains how to Select Radio Buttons in Selenium including Code Implementation & various Methods for Selecting Radio Buttons on a Web Page:

A Radio button is nothing but a graphical element that controls the selection of options, thereby allowing the user to select any one option from a set of options. It is also known as the options button.

Radio buttons are so-called because of the functionality they have like channels of Radio i.e. only one button can be selected at a time.

Selenium is one of the most popular automation testing tools that handles working of almost all operations and the Radio button is one among them. Let’s explore the use of an automation tool to understand the functioning of a Radio button.

=> Check ALL Selenium Tutorials Here

Handling Radio Buttons in Selenium

In this tutorial, we will see how to handle Radio buttons using Selenium.

Radio Buttons In HTML

Let’s first understand the use of a Radio button in HTML Page. In HTML, the Radio button is used to select one option among a list of the provided options.

Check the below example to understand how Radio buttons are created in HTML.

<html>

<head>
<title> Confirmation </title>
</head>

<body>
<form>
<h2> Select a Radio button for confirmation </h2>
<input type="radio" name="confirm" value="Yes">Yes<br>
<input type="radio" name="confirm" value="No">No<br>
<input type="radio" name="confirm" value="May Be">May Be<br>
</form>
</body>

</html>

Where,

  • type: Input tag having type attribute. It would mostly be ‘Radio” for radio buttons.
  • name: It is the name of the Input element. A set of Radio buttons with the same name are said to form a Radio group.
  • value: It is the actual value corresponding to its Radio button.

Enlisted below are some more points in addition to the above:

  1. The HTML page is named as “Confirmation”.
  2. It has the title “Select a Radio button for confirmation”.
  3. Three Radio buttons are provided: Yes, No, May Be.

The below image gives a clear idea of the created HTML page.

Select Radio button

Code Implementation To Handle Radio Buttons In Selenium

Selection of a Radio Button in which we got to choose only one option at a time enables the user to select either of the options among the list of the provided options. The below implementation would give a clear idea of handling Radio buttons using Selenium WebDriver.

Given below is a screenshot of the Html page that includes the Radio button section. The below Html page that has a set of radio buttons for selection of color and size is created and used for testing.

radio buttons for selection of colour and size

Implementation code for Radio button selection:

package project1;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

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

public class radio {

	public static void main(String[] args) throws IOException {
        
		WebDriver driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.manage().window().maximize();
		driver.get("file:///E:/Selenium class/Programs/Sonali/bin/project1/form2selenium.html");	

		WebElement radio = driver.findElement(By.xpath("//input[@id='i-green']"));
		radio.click();

                            WebElement radio2 = driver.findElement(By.xpath("//input[@value='Medium']"));
		radio2.click();
}
}

The output received after executing this code is as shown in the below screenshot:

Output - Radio Button for colour

Methods For Selecting Radio Elements Using Selenium

Selenium includes different ways using which we can select the Radio elements on a Web Page.

The different methods are as below:

  1. By ID attributes
  2. Using Is Selected()
  3. Using Name
  4. Using element Value
  5. By CSS Selector
  6. With XPath

Consider the below image for understanding the examples of each of the selection methods:

selection methods

#1) Using ID Attributes

In this case, we just need to use the ID attribute, regardless of whatever its value is. The ID attribute is used in Selenium for selecting the desired Radio button. ID attributes are different for different elements.

For example:

WebElement radio = driver.findElement(By.id("i-red"));
radio.click();

OR

WebElement radio1 = driver.findElement(By.id("i-green"));
radio1.click();

OR

WebElement radio2 = driver.findElement (By.id("i-yellow"));
radio2.click();

As shown in the above image, there are six Radio buttons i.e. Red, Blue, Green, Yellow, Gray, and Black. For selecting a Radio button from these, we can make use of ID attributes in Selenium for Radio button selection in this way.

The below image highlights the id attributes for the above options.

Image highlighting id Attributes

#2) Using Is Selected()

Use of Is Selected() enables the user to ensure whether a particular Radio button is in checked mode or not. In simple words, the selection of the Radio button is confirmed.

For example:

List radio = driver.findElements(By.name("colour”));

//same group of Radio buttons always have same 'Names', 
//hence we need to use findElements method and store the list of Web elements.

boolean bval = false;		 // create a variable which will have boolean value True/False
bval = radio.get(0).isSelected();	 // will return True if button is selected.

if(bval = true)
{
radio.get(1).click(); // if the first radio button is selected by default, this will select Second radio button
}
else
{
radio.get(0).click(); // if the first radio button is not selected by default, the first will be selected
}

#3) Using Name

For Selecting Radio buttons using Name, we need to understand one important point i.e. For Radio Buttons in the same group (Radio Group), Name is always the same but their Values are different.

So if any element with the name attribute is found, then it might contain more than one element, thus we need to store the list of WebElements and make use of the findElements method.

List radio = driver.findElements(By.name("colour"));

This was used in the previous example for Is Selected() as well.

#4) Using Element Value

Radio buttons can be selected with the help of their Values too.

Each button has a unique value. The use of the Values for selecting the Radio buttons can be as shown in the below example.

List RadioButton = driver.findElements(By.name("colour"));
           // selecting the Radio buttons by Name

 	       int Size = RadioButton.size();		         // finding the number of Radio buttons

 	       for(int i=0; i < Size; i++)		    	       // starts the loop from first Radio button to the last one
	      {	
	 	String val = RadioButton.get(i).getAttribute("value");
    // Radio button name stored to the string variable, using 'Value' attribute

	 	if (val.equalsIgnoreCase("Green"))   // equalsIgnoreCase is ignore case(upper/lower)
	             {				   // selecting the Radio button if its value is same as that we are looking for
		RadioButton.get(i).click();
		break;
	    	}
	          }

#5) By CSS Selector

Another way for selecting Radio elements is by CSS Selector using its value.

The below example will explain the same:

WebElement rbutton = driver.findElement(By.cssSelector("input[value=' Yellow']"));
rbutton.click();

#6) Using XPATH

Selecting a Radio element using XPATH is one of the ways for Radio element selection in Selenium that helps to select the exact element you wish to select.

Look at the below example for selecting the Radio button using XPATH.

WebElement radio_b1 = d.findElement(By.xpath("//input[@id='i-red']"));
radio_b1.click();’

OR

WebElement radio_b2 = d.findElement(By.xpath("//input[@id='i-green’]"));
radio_b2.click();

OR

WebElement radio_b3 = d.findElement(By.xpath("//input[@id=’i-gray’]"));
radio_b3.click();

Examples/Applications Where Radio Buttons Are Used

There are a vast number of uses of Radio Buttons and a few of them are mentioned below.

#1) Gender Selection:

Gender Radio button

#2) Field Selection:

field radio button

#3) Choose an Email Account:

Mail account radio button

[image source]

#4) Customer Survey Forms:

Customer survey forms

#5) Availability Status In An Application:

Availability status Radio button

There are many more such examples that we come across in our daily work. All these examples have one thing in common i.e. you got to choose a single option at a time. Thus, Radio buttons give a clear idea of what exactly the customer opts to choose.

Few Other Examples:

  1. Colour selection: Red/ Blue/ Green/ Yellow.
  2. Field/Course selection: Arts/ Commerce/ Science.
  3. Type of address: Permanent/ Temporary.
  4. Education level: School/ College/ Working.
  5. Mode of payment: NetBanking/ GooglePay/ AmazonPay.
  6. Choose a language during app installation: English/ Russian/ French/ German/….
  7. Type of password protection: Text Password/ Zip Code/ Pattern/ Finger Print.
  8. Mode of transport: Car/ Bike/ Public Transport.
  9. Insurance type: Medical/ Dental/ Vision/ Medical Supplement.
  10. Select student’s grade on the report card: Grade A/ Grade B/ Grade C/ Grade D.

States Of Radio Buttons

We have already seen the uses of Radio Buttons. Now, let’s look at its different states along with their significance.

states of Radio Button

  1. Normal: This state is nothing but the default option or default state.
  2. Hover: The hover effect as it is visible, tells users that it is a clickable target. Also, it prepares the user to click the option, after seeing the hover effect.
  3. Checked: This state specifically shows the radio option which is selected. The selected option is color-filled and can be easily identified as a selected option among the other options.
  4. Disabled: Once an option is selected by the user, the remaining options might automatically fade out and the user has no choice to select any option among the remaining. These are known to be in disabled states, as it is only one option that can be selected at a time.
  5. Disabled & Checked: On selecting a particular option, if the Radio button is disabled, it is to confirm the selection. That is you choose an option and it is frozen as confirmed. One can easily identify this option as compulsorily selected.

How Are Radio Buttons Different From Checkbox?

Radio Button Check Box
Allows only one option selection at a time.Allows multiple options selection at the same time.
It has 2 major conditions: True or False.It can be Checked, Unchecked and/or Indeterminate.
Usually represented as a circular button.Usually represented with a square box.
Example - Selecting recent qualification:
-Graduate
-Post- Graduate
Only one selection is possible either Graduate or Post- Graduate to specify latest qualification using Radio button.
Example - Selecting subjects for training:
-Mathematics
-Physics
-Chemistry
-Computer Fundamentals
-Basic Electrical Engineering
One or more or all options can be selected by use of check box.

Conclusion

We have understood the working or handling of Radio buttons using Selenium in detail. We have also seen different methods for selecting Radio elements using Selenium.

Through this tutorial, we have understood the states of Radio buttons and the various examples where Radio buttons are used. One thing is sure that, in the case where only one option satisfies the answer (either/ or) provided among various options, in those cases, Radio Buttons are recommended to use.

We hope you enjoyed this informative tutorial on Handling Radio Buttons In Selenium!

=> Read Through The Complete Selenium Guide