How To Select The Check Box In Selenium With Examples

This Tutorial Explains Various Methods To Select Check Box In Selenium With Examples. You will also learn to Select Multiple Checkboxes & CheckBox in HTML:

We saw how Radio buttons are handled in Selenium in one of our earlier tutorials. Now, let’s the functioning of the Checkbox in Selenium.

The checkbox is a Web element that is used for the selection of one or multiple options, as a result of the answer to the provided question.

The checkbox can be turned on or off (that is checked or unchecked). A checked Checkbox is the one that is seen as the tick marked. Unchecked is the one that is unticked.

=> Watch Out The Simple Selenium Training Series Here.

Handling Check Box in Selenium

The image below clearly shows the checkboxes, where the first 2 can be seen checked while the last one is unchecked.

tick

The checkbox is also known as Selection Box or Tick Box. The small box inside which a tick mark appears on clicking the Checkbox and when clicked again, the checkmark disappears and the box is unchecked.

In this tutorial, we will explore the handling of Checkbox in Selenium.

Select A Checkbox Using Keyboard

Open the website you are working on or that has a Checkbox you want to select.

Press the Tab button until the Checkbox you want to select is highlighted. Once the desired Checkbox is seen highlighted i.e. the cursor reaches the Checkbox, then use the Space Bar button to check or uncheck the box.

Go to any website that has a checkbox to select and try it out.

tick a check box using keyboard

Checkbox In HTML

Let us first understand the use of Checkboxes in HTML Page. In HTML, Checkbox is used to select one or more options amongst a list of provided options.

See the below example to understand Checkboxes created in HTML.

<html>

<head>
<title> Check Boxes html page</title>
</head>

<body>
<form>
<h2> Choose the subjects included in your syllabus </h2>

<input type="checkbox" name="sub" value="Computer Fundamentals">Computer Fundamentals<br>
<input type="checkbox" name="sub" value="Electrical">Electrical<br>
<input type="checkbox" name="sub" value="Physics">Physics<br>
<input type="checkbox" name="sub" value="Chemistry">Chemistry<br>
<input type="checkbox" name="sub" value="None">None<br>
</form>
</body>

</html>

Where,

  • type: Input tag having type attribute. It would be ‘checkbox” for Check boxes.
  • name: It is the name of the Input element.
  • value: It is the actual value corresponding to its Checkbox.

In addition to the above, some more points are given below:

  1. The HTML page is named as “Checkboxes html page”.
  2. It has the title “Choose the subjects included in your syllabus”.
  3. Five Checkboxes are provided: Computer Fundamentals, Electrical, Physics, Chemistry, None.

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

checkbox in html

Implementation Of Code For Handling Checkbox In Selenium

Let’s look at the Handling of Checkbox using Selenium. With this code, we will understand, how the operations of Checkbox are carried out by the use of Selenium.

For implementing code in Selenium for Checkbox, we have used this link, and the screenshot for the same is as below:

Single & Multiple Check box Demo

Implementation code for Handling CheckBox using Selenium:

package SeleniumPrograms;

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

public class CheckBox1 {

public static void main(String[] args) {

	WebDriver driver = new FirefoxDriver();
	dr.manage().window().maximize();
	dr.get("https://www.seleniumeasy.com/test/");
		
	WebElement input = dr.findElement(By.className("dropdown-toggle"));
	input.click();
		
	WebElement checkbox = dr.findElement(By.linkText("Checkbox Demo"));
	checkbox.click();
	System.out.println("Check Box..");
		
	WebElement check1 = dr.findElement(By.xpath("//input[@id='isAgeSelected']"));
	check1.click();
	System.out.println("Clicked Check Box..");
		
	WebElement checkall = dr.findElement(By.xpath("//input[@id='check1']"));
	checkall.click();
	System.out.println("Checked all Boxes..");
	
        }

}

Thus, on implementing the above code, the Output received is as shown in the below image.

seleniumeasy

First, only one Checkbox is checked, after which a message is received as “Clicked CheckBox”. Then, for multiple Checkboxes, we have the option to check one, two, three, or all Checkboxes at the same time. On choosing “Check All”, all Checkboxes are checked at the same time.

code_console

Select Multiple Checkboxes In Selenium

When there are multiple options and multiple checkboxes provided for the same, we can code it in such a way that on executing the code all the checkboxes would be checked. So, let us look at the code for handling multiple Checkboxes.

We have created an HTML page, for implementing code for handling multiple Checkboxes, and below is the screenshot of the same.

multiple checkbox

package Practice;

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

   public static void main(String[] args) {

	WebDriver driver = new FirefoxDriver();
	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	driver.manage().window().maximize();
	driver.get("E:\\Selenium class\\Programs\\Sonali\\bin\\project1\\check.html");
		
	List<WebElement> AllCheckBoxes = driver.findElements(By.xpath("//input[@type='checkbox']"));
	System.out.println("Number of Check boxes : "+ Integer.toString(AllCheckBoxes.size()));
	    
	for(WebElement cb:AllCheckBoxes)
	{
		cb.click();
	}
	System.out.println("All check boxes have been checked");
      }
}

Thus, we can handle multiple Checkboxes. This was just an example, and you can try it with any other website where multiple Checkboxes are present with multiple options.

Given below is the screenshot of the above implementation of multiple Checkboxes in Selenium.

multiple checkedall

output2

Thus, multiple Checkboxes can be handled with the help of Selenium.

Methods To Select Checkbox In Selenium

There are different ways in Selenium using which we can select the Checkbox 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

Check Boxes and Radio Buttons are handled similarly and we can use all of the above selection methods for both.

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

unchecked_seleniumeasy

#1) Using ID Attributes

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

For example:

WebElement check = driver.findElement(By.id(“isAgeSelected"));
check.click();

Thus, we can make use of ID attributes in Selenium for Checkbox selection.

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

Id attributes

#2) Using Is Selected()

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

For example:

List check = driver.findElements(By.className("cb1-element"));

//Same group of check boxes will have same 'Names'/Class names,
//hence we need to use findElements method and store the list of WebElements.

boolean bval = false;		 // Create a variable which will have boolean value True/False
bval = check1.get(0).isSelected();	 // Will return True if box is selected.

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

#3) Using Class name

For selecting Checkboxes using Name or Class name, we need to understand one important point which is:

For Checkboxes in the same group, Name/Class name will always be 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 check = driver.findElements(By.className("cb1-element"));

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

#4) Using element Value

Checkboxes can be selected with the help of their Values too.

Each box has a unique value. The use of Values for selecting Checkboxes can be as shown below.

// Selecting the check boxes by class name
List checkbox = driver.findElements(By. className("cb1-element"));

        int Size = checkbox.size();		// Finding the number of check boxes

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

if (val.equalsIgnoreCase("cb1-element "))
// equalsIgnoreCase is ignore case (upper/ lower)	
	{		
                 // Selecting the check box if its value is same as that we are looking for
		checkbox.get(i).click();
		break;
	 }
   }

#5) By CSS Selector

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

Example:

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

#6) Using XPATH

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

Look at the below example for selecting Checkbox using XPATH.

WebElement check_box = d.findElement(By.xpath("//input[@id='isAgeSelected'] "));
check_box.click();

Examples/Applications Where Checkbox Is Commonly Used

#1) Favorite Sports

The checklist in the below image contains different sports activities. We can select one or more options from it. The checked boxes can be seen as highlighted.

Sports

#2) Use Of Checkbox To Confirm An Agreement

The checkbox is provided for confirmation. Once the user tick marks this checkbox, the system considers the user’s acceptance to the agreement and continues further.

agree

youtube-i-agree-terms-service-privacy-policy

#3) Language Selection

For selecting a language, a Checkbox can be used. It allows users to select one or more options.

language-selection

[image source]

#4) Adjusting Settings With The Use Of Checkbox

The below image shows the selection of Checkbox for different preferences. As per the user’s choice, the options can be selected.

Adjusting settings with the use of Check box

[image source]

#5) Selecting The Fitness Programs Of Your Choice

Different fitness program options are provided and the user has to choose those of his choice.

Selecting the fitness programs of your choice

[image source]

#6) Choose Colors

Checkboxes are provided for the selection of colors too.

Choose Colours

There are numerous such examples where checkboxes are used.

To mention a few more:

  1. Choose Subjects: Mathematics, English, Physics, Chemistry, All.
  2. Select break time: 9 AM, 12 PM, 3 PM, 6 PM, None.
  3. Vehicles you have: Bike, Car, both, None.
  4. Testing Skills: Manual, Automation, Both, None.
  5. Metals used: Gold, Silver, Platinum, Mixed.
  6. Countries where products are available: Belgium, Colombia, France, Germany.
  7. Select your hobbies: Painting, Artwork, Singing, Dancing, Gardening.
  8. Vegetable List: Capsicum, Cauliflower, Cabbage, Potatoes, Tomatoes.
  9. Fruits Check List: Pineapple, Apple, Watermelon, Oranges, Mangoes.
  10. Cell Phones used in a house: I Phone, One Plus, Nokia, Samsung, Blackberry, Other.

States Of Checkbox

There are 3 major states of Check Boxes:

threestate

#1) Checked: State in which the Checkbox is selected is the checked state. Here, we can see the box as tick marked.

#2) Unchecked: Box which is not tick marked or when the selected box is clicked again, then the box goes in an unchecked state.

#3) Intermediate: When a box is neither in checked nor in the unchecked state, it is known to be an intermediate state. In this state, the user has the option to choose whether he wishes to click the box or not.

The above image will help you to understand these states.

checkbox_three_state_intermediate

The above image is one more such example that explains the different states of Checkboxes.

  • Checked State: Enable feature XYZ
  • Unchecked State: Enable feature ABC, Enable feature WWW
  • Intermediate State: Enable all.

Thus, Checked, Unchecked, and Intermediate states of Checkbox are as explained above.

Conclusion

We have seen the handling of Checkbox using Selenium in detail. Thus, Checkboxes enable users to select more than one option. We have seen numerous uses of Checkbox that allow the users to select multiple options at the same time.

We explored the methods for the selection of Checkbox elements and understood the handling of multiple Checkboxes using Selenium.

Happy Reading!!

=> Visit Here To Learn Selenium From Scratch.