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 that they enhance the functionality of a web page by allowing the user to choose from multiple options.
Today, we’ll tell you how you can use the Webdriver to perform operations on such elements. Though these fields are slightly different from the other HTML elements, it’s easy to access them using the ID attribute which is most of the time the same for both of these.
How to Automate Checkbox and Radio Button
There are many actions that you can perform on these elements like the selection or deselection, checked or unchecked, and verifying their default state.
How to select these elements?
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 an HTML form and the example code for the hands-on. You may also love to try out Selenium Webdriver quizzes on our blog.
Use ID for selection
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();
Call IsSelected() to check the state
If you’ve selected/deselected a Checkbox/Radio Button and you want to check its final state. Then, you can use the <IsSelected> command to know 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("https://techbeamers.com"); // Sleep for 5 seconds Thread.sleep(5000); // Store all the elements of the same category in the list of WebLements. List 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.
Use element value for selection
One of the intuitive ways to select the Radio Buttons/CheckBoxes 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("https://techbeamers.com"); // Sleep for 5 seconds Thread.sleep(5000); // Find the checkbox or radio button element by its name. List 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; } } } }
CssSelector to select
Another easy way to select/deselect these elements is by using the cssSelector. Please refer to 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();
HTML form and example code for hands-on
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 form
<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. We’ve listed down the summary of the actions that this code is executing.
Example
– Create the Firefox instance and load the HTML form in the browser.
– Set the Webdriver implicit wait to 10 seconds.
– Get the total count of checkboxes and radio buttons.
– Select all of them.
– 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 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 – Handle Checkbox and Radio Button
There are many interesting Selenium Webdriver 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