Checkbox and Radio Button Operations In Webdriver

In the world of web automation, it is quite common to automate the sign-up forms which contain checkbox and radio button elements. These fields are unique in a way as they extend the functionality of a form by allowing the user to choose from multiple options. Today, we’ll tell you how you can use the Webdriver to perform checkbox and radio button operations. Though these fields are slightly different from the other HTML elements, yet it’s easy to access them using the ID attribute which is most of the times same for both of these. There are many operations that you can perform on these elements like the selection or deselection, checked or unchecked and verifying the default state of a checkbox and radio buttons.

In this post, we’ll cover the different methods for selecting the checkbox and radio button elements. Then, there’ll be a practice exercise where we’ll give you a HTML form and the example code for the hands-on. You may also love to try out mind-boggling Selenium Webdriver quizzes on our blog.

  1. Various methods to select checkbox and radio button.
    1. Use ID for Selecting Checkbox/Radio button.
    2. Use IsSelected Method to Check the State of Checkbox/Radio button.
    3. Use Element Value for Selecting Checkbox/Radio button.
    4. Use CssSelector for Selecting Checkbox/Radio button.
  2. HTML form and example code for hands-on practice.

Checkbox and Radio Button Operations In Webdriver.

1- Various methods to select checkbox and radio button.

1.1- Use ID for Selecting Checkbox/Radio button.

You can use the ID attribute to select a Radio Button or a CheckBox. We’ve provided the Webdriver command to click which you can apply to both types of elements.

// Java code example to select checkbox/radio button.

WebElement target = driver.findElement(By.id("checkbox1"));

target.click();

 

1.2- Use IsSelected Method to Check the State of Checkbox/Radio button.

If you’ve selected/deselected a Checkbox/Radio Button and you just want to check its final state. Then, you can use the <IsSelected> command to know that the correct status of the element.

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 findElementsTest {

	public static void main(String[] args) throws Exception {

		// Launch browser
		WebDriver driver = new FirefoxDriver();

		// Maximize window
		driver.manage().window().maximize();

		// Navigate to the URL
		driver.get("http://www.techbeamers.com");

		// Sleep for 5 seconds
		Thread.sleep(5000);

		// Store all the elements of the same category in the list of WebLements.
		List<WebElement> list = driver.findElements(By.name("radioButton"));

		// Create a boolean variable to store true/false.
		Boolean is_selected = list.get(0).isSelected();

		// If 'is_selected' is true that means the first radio button is
		// selected.
		if (is_selected == true) {

			// If the first radio button is selected by default then,
			// select the second radio button.
			list.get(1).click();

		} else {

			// If the first radio button is not selected then, click the first
			// radio button.
			list.get(0).click();
		}
	}
}

 

Note: When there is a group of Radio Buttons/Check Boxes on the page then, it is possible that their names are same, but values are different. That’s why we’ve used the Webdriver findElements command to get the list of web elements.

 

1.3- Use Element Value for Selecting Checkbox/Radio button.

One of the intuitive ways to select the Radio Buttons/Check Boxes is by toggling their Values. Please follow the below code example for more clarity.

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 findElementsTest {

	public static void main(String[] args) throws Exception {

		// Launch browser
		WebDriver driver = new FirefoxDriver();

		// Maximize window
		driver.manage().window().maximize();

		// Navigate to the URL
		driver.get("http://www.techbeamers.com");

		// Sleep for 5 seconds
		Thread.sleep(5000);

		// Find the checkbox or radio button element by its name.
		List<WebElement> list = driver.findElements(By.name("checkbox"));

		// Get the number of checkboxes available.
		int count = list.size();

		// Now, iterate the loop from first checkbox to last checkbox.
		for (int i = 0; i < count; i++) {

			// Store the checkbox name to the string variable, using 'Value'
			// attribute
			String sValue = list.get(i).getAttribute("value");

			// Select the checkbox if its value is the same that you want.
			if (sValue.equalsIgnoreCase("checkbox")) {

				list.get(i).click();

				// This statement will get you out of the for loop.
				break;
			}

		}
	}
}

 

1.4- Use CssSelector for Selecting Checkbox/Radio button.

Another easy way to select/deselect a checkbox or a radio button is by using the cssSelector. Please refer the below code snippet to bring more clarity.

// Java example code to select a checkbox using the cssSelector.

WebElement checkBox = driver.findElement(By.cssSelector("input[value='TechBeamers']"));

checkBox.click();

 

2- HTML form and example code for hands-on practice.

Below is the HTML code of the input form which you can save as an HTML file locally to practice the checkbox and radio button operations.

<html>  
  <head>  
    <title>Perform Checkbox and Radio Button Operations.
    </title>  
  </head>  
  <body>  
    <form name="testform" action="" method="POST">  
      <div align="center">
        <br>  
        <input type="checkbox" name="option-1" value="Java">Java  
        <input type="checkbox" name="option-2" value="C++">C++   
        <input type="checkbox" name="option-3" value="Python" checked>Python  
        <input type="checkbox" name="option-4" value="PHP">PHP   
        <input type="checkbox" name="option-5" value="CSharp">CSharp  
        <input type="checkbox" name="option-6" value="Ruby">Ruby  
        <input type="checkbox" name="option-7" value="Perl">Perl  
        <br>  
        <input type="radio" name="group-1" value="Programming"> Programming  
        <input type="radio" name="group-1" value="Testing"> Testing  
        <input type="radio" name="group-1" value="Test Automation" checked> Test Automation  
      </div>  
    </form>  
  </body>  
</html>

 

If you’ve copied the above HTML code to a file, then run the below Java code in Eclipse IDE to perform the checkbox and radio button operations. We’ve listed down the summary of the actions which this code is executing.

  1. Create the FireFox instance and load the HTML form in the browser.
  2. Set the Webdriver implicit wait to 10 seconds.
  3. Get the total count of checkboxes and radio buttons.
  4. Select all of the check boxes and radio buttons.
  5. Close the Firefox instance.
import java.util.List;
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 PracticeFormCheckBoxAndRadioButton {

	public static void main(String[] args) throws InterruptedException {

		// Create FireFox browser object.
		WebDriver firefox = new FirefoxDriver();

		// Now maximize the browser window.
		firefox.manage().window().maximize();

		// Start the FireFox browser and open the page.
		// Provide the correct path of the HTML file.
		firefox.get("PracticeFormCheckBoxAndRadioButton.html");

		// Set timeout value.
		firefox.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

		// Get the count of all available checkboxes.
		List<WebElement> list = firefox.findElements(By.tagName("input"));

		// Below code will select all of the check boxes and radio buttons.
		for (int i = 0; i < list.size(); i++) {
			// Checking the check box
			if (list.get(i).getAttribute("type").trim()
					.equalsIgnoreCase("checkbox")) {

				// Show the Checkbox count with value.
				System.out.println("CheckBox = " + i + " "
						+ list.get(i).getAttribute("value").trim());

				// Select the check box if not already selected.
				if (!(list.get(i).isSelected())) {
					list.get(i).click();
				} else {
					// De-select the check boxes.
					list.get(i).click();
				}
			} // Checking the Radio buttons.
			else if (list.get(i).getAttribute("type").trim()
					.equalsIgnoreCase("radio")) {

				// Show the size of radio buttons.
				System.out.println("Radio  = " + i + " "
						+ list.get(i).getAttribute("value").trim());

				// Select the radio button if not already selected.
				if (!(list.get(i).isSelected())) {
					list.get(i).click();
				}
			}

			// Pause so that you can see the results.
			Thread.sleep(5000);
		}

		// close the FireFox browser instance.
		firefox.close();
	}
}

 

Final word.

There are many interesting tutorials on our blog which you can refer to build your automation skills. We wish you well in your learning journey

If you liked the above Webdriver tutorial, then please care to share it on the social media of your choice.

 

Best,

TechBeamers.