App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide How to handle Checkbox in Selenium

How to handle Checkbox in Selenium

By Sonal Dwivedi, Community Contributor -

What is a Checkbox?

Checkbox, also known as Selection box or tick box is a small interactive box on a web page that allows a user to select one or more options. On selecting the checkbox, a tick mark is displayed inside the checkbox indicating that the particular option is selected. To deselect a checkbox user may simply click on the checkbox to deselect the already selected option. It facilitates the user to select single or multiple options from a list of choices and the web page may remember it for future use.

When working in web automation, like any other web element such as input box, button, links, checkbox should also be automated. Let us deep dive to understand how we can do that with the help of Selenium.

How to handle Checkbox in Selenium?

Before jumping to how to select/deselect a checkbox on a web page using Selenium, let us first learn how to locate a checkbox using Selenium. Selenium offers various locator strategies and almost all of them can be used to locate a check box. Let us see some one of them with an example.

Using W3Schools website to demonstrate locating checkboxes on web pages using Selenium.

W3Schools

Click on “Try it Yourself button” to land to
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox

(Note: If the above practice page appears broken for you, you may simply search “w3schools checkbox” on Google.com to get the desired practice web page)

Locate checkbox using Id locator

If a checkbox element has an id attribute which is unique, we can use the ID locator of Selenium WebDriver to locate a checkbox. A checkbox in the DOM is defined using the input tag with the type as ‘checkbox’.

Example: 

<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">

Id

You can see from the above image that the “I have a bike” checkbox has an input tag with type=’checkbox’ and id=’vehicle1’. If we need to locate this checkbox with ID locator below would be the Selenium code:

WebElement bike=driver.findElement(By.id("#vehicle1"));

Selecting Checkbox in Selenium

To select any checkbox we need to use the click() method of the WebElement interface of Selenium.

bike.click();

After the click operation, the checkbox should appear to be selected as shown in below image:

checked

Locate checkbox using name locator

If a checkbox element has a name attribute which is unique, we can use the name locator of Selenium WebDriver to locate a checkbox.

You can see from the above image that the “I have a bike” checkbox has the name=’vehicle1’. If we need to locate this checkbox with name locator below would be the Selenium code:

WebElement bike=driver.findElement(By.name("vehicle1"));

To select any checkbox we need to use the click() method of WebElement Interface of Selenium.

bike.click();

Locate checkbox using XPath locator

Sometimes Selenium cannot find a checkbox with just the id or name value or any other attribute, and therefore XPath is considered in such cases.

You can see from the above image that the “I have a bike” checkbox has an input tag with name=’vehicle1’ and id = ‘vehicle1’. If we need to locate this checkbox with XPath locator below would be the Selenium code:

WebElement bike=driver.findElement(By.xpath("//input[@name='vehicle1' and @id='vehicle1']"));

To select any checkbox we need to use the click() method of WebElement Interface of Selenium.

bike.click();

Locate checkbox using CSSSelector

Like XPath, CSSSelector can also be used if Selenium cannot find a checkbox with just the id or name or any other attribute value.

You can see from the above image that the “I have a bike” checkbox has an input tag with type=’checkbox’, id = ‘vehicle1’. If we need to locate this checkbox with CSSSelector locator below would be the Selenium code:

WebElement bike=driver.findElement(By.cssSelector ("input#vehicle1"));

To select any checkbox we need to use the click() method of WebElement Interface of Selenium.

bike.click();

Locate checkbox using Attribute value

Sometimes a group of checkboxes may have the same name or class or id value, which makes it difficult to check a single checkbox. In such cases, checkboxes can be located by using their value attribute as each checkbox has a unique value assigned to it.  

value

If we need to locate “I have a bike” checkbox with value attribute we can use CSSSelector and below would be the Selenium code:

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

To select any checkbox we need to use the click() method of WebElement Interface of Selenium.

bike.click(); 

How to Select multiple options in Checkbox using Selenium

In the above example, we learned that in some web pages, there may be a group of checkboxes which have the same name/class/id attribute and therefore choosing the checkbox with respect to their value attribute is the best option if we need to click on a single checkbox. 

And if there is a need to select multiple checkboxes which have the same name/id/class attribute but different attribute values, creating different web elements and then clicking on it one by one would be cumbersome. Instead we can create a list of web elements and iterate through it sequentially and click on it.

Let us see how we can select all checkboxes in the above example with the below Selenium code.

  • First, we will create a List of web elements to store all the checkboxes.
List<WebElement> chkboxes=driver.findElements(By.cssSelector("input[type='checkbox']"));
  • Then we need to find out the size of the web element list.
int size=chkboxes.size();
  • Then using the for loop and get() method we will iterate through all the check boxes and click on it using the click() method.
chkboxes.get(i).click();

Complete code: 

public class CheckBox {

public static void main(String args[]) {

     WebDriver driver=new ChromeDriver();

        driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox");

             //Switch to the iframe which contains the checkboxes

        driver.switchTo().frame("iframeResult");

            

     List<WebElement> chkboxes=driver.findElements(By.cssSelector("input[type='checkbox']"));

     int size=chkboxes.size();

     for (int i=0; i<size; i++) {

         chkboxes.get(i).click();

     }

}

}

Validations on a checkbox using Selenium

To validate pre and post conditions of checkbox’s state, Selenium provides certain methods which are as follows:

  • isEnabled(): A pre-validation for checkbox click event to check whether the checkbox is enabled or disabled on the web page. This method returns true in case element is enabled otherwise it returns false.
  • isDisplayed(): A pre-validation for checkbox click event to check whether the checkbox is displayed on the web page or not. It returns true if the desired element is displayed on DOM otherwise it returns false.
  • isSelected(): A post-validation after the checkbox click event to check whether the checkbox is selected or not. It returns true if the element is selected, else false for deselected.

Suppose there is a scenario where the user needs to first check the visibility of the checkbox and based on the visibility it needs to be selected. So in such a condition we can use isDisplayed() method as a precondition and on the basis of its result either true or false, the checkbox can be selected.

public class CheckBox { 

public static void main(String args[]) {

     WebDriver driver = new ChromeDriver();

        driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox");

     // Switch to the iframe which contains the checkboxes

        driver.switchTo().frame("iframeResult");

     WebElement car = driver.findElement(By.cssSelector("input#vehicle2"));  

        System.out.println("car.isDisplayed()" + car.isDisplayed());

     if(car.isDisplayed()==true) {

         car.click();        

     }else {

         System.out.println("Option is not displayed");

     }

}

}

How to assert that a checkbox is checked?

If there is a need to validate whether the checkbox is selected after selecting the desired checkbox, we can use isSelected() method which returns true if the checkbox is selected and false in either case. The Selenium code to test this scenario is as follows:

public class CheckBox {

public static void main(String args[]) {

     WebDriver driver = new ChromeDriver();

        driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox");

     // Switch to the iframe which contains the checkboxes

        driver.switchTo().frame("iframeResult");

     WebElement car = driver.findElement(By.cssSelector("input#vehicle2"));

     car.click();

        System.out.println("car.isSelected()" + car.isSelected());

     if(car.isSelected()==true) {

         System.out.println("Option is selected");

     }else {

         System.out.println("Option is not selected");

     }

}

}

How to Deselect Checkbox in Selenium

At the start of this article we learnt that the click() method of WebElement interface is used to click a checkbox. Similarly, to deselect a checkbox, the same click() method is used.

However, in web automation it is a good practice to check the state of the checkbox before deselecting it, otherwise clicking to deselect the checkbox will select the checkbox if the checkbox was not in a selected mode previously.

public class CheckBox { 

public static void main(String args[]) {

     WebDriver driver = new ChromeDriver();

        driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox");

   //Switch to the iframe which contains the checkboxes

        driver.switchTo().frame("iframeResult");

     WebElement car = driver.findElement(By.cssSelector("input#vehicle2"));

     //car.click();

        System.out.println("car.isSelected()" + car.isSelected());

     if (car.isSelected()) {

         car.click();

         System.out.println("Car deselected");

     }else {

         System.out.println("Car is already deselected");

     }

}

}

Conclusion

This article discussed how to locate a checkbox on a web page with different Selenium locator strategies, how to select and deselect it, and validate that the checkbox is selected or not. It is recommended that when testing the checkboxes on your testing web application you should test is on real devices and browsers for more accurate test results.

Using BrowserStack’s real device cloud which provides 3000+ real devices and browsers you can test your web application comprehensively. It supports cross-browser testing and delivers a seamless user experience across browsers and devices.

Try BrowserStack Now

Tags
Selenium Selenium Webdriver Website Testing

Featured Articles

Locators in Selenium: A Detailed Guide

Understanding Selenium Click Command

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.