TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Handle Checkbox & Radio Button in Webdriver
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Selenium Tutorial

Handle Checkbox & Radio Button in Webdriver

Last updated: Mar 03, 2024 12:20 pm
By Harsh S.
Share
8 Min Read
Checkbox and Radio Button Operations In Webdriver
Checkbox and Radio Button Operations In Webdriver.
SHARE

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.

Contents
How to select these elements?Use ID for selectionCall IsSelected() to check the stateUse element value for selectionCssSelector to selectHTML form and example code for hands-onHTML formExample

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

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

TAGGED:Advanced Selenium Tutorial

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article findElement and findElements Commands and Examples FindElement and FindElements Commands
Next Article Handling DropDown And Multiple Select Operations in Webdriver DropDown And Multiple Select in Webdriver

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x