Working with Checkbox in Selenium

Handling check box in Selenium

Handle Check boxes with Selenium

Working with checkbox is similar to handling radio buttons. In our previous chapter we learnt how to get the reference of radio button WebElement and perform various operations like selecting a radio button, fetch information if the radio button is selected or not etc. and we will use this knowledge to automate check boxes too.

The only fundamental difference in a check-box and a radio button is – check boxes are multi select in nature. You may select multiple check boxes as an option/response. Let’s dive deep into the HTML of checkbox. Navigate to http://www.echoecho.com/htmlforms09.htm and inspect element for the checkbox WebElement, as shown in following figure:

Handling check box in Selenium

HTML structure for checkbox is similar to radio button. Like radio buttons, here also we have tags and attributes combination, “check” attribute to confirm which checkbox(es) is/are currently selected etc.

Checkbox Name
HTML Tag
HTML Attribute(name)
HTML Attribute
(value)
Milk
input
option1
Milk
Butter
input
option2
Butter
Cheese
input
option3
Cheese

Don’t worry about “Checkbox Name” column, it is only representation of the checkbox. The real meat are the tags and attributes which constitutes a checkbox.

In our example, all the check boxes have different “name” attribute hence we cannot traverse all the check boxes using “name” attribute. Also, similar to radio buttons, selected check boxes have “checked” attribute written against them and in case of check boxes “checked” attribute could occur more than once since user can select more than one checkbox.

Selecting a Checkbox

Let us try to select “Cheese” checkbox. It has “option3” as name attribute and we will make use of it.

WebElement checkBoxSel = driver.findElement(By.name("option3"));
checkBoxSel.click();

Above code will store the “Cheese” checkbox reference in “checkBoxSel” variable, which is of type WebElement and then we can perform all the operations which could be done on a checkbox, like selecting it.

Verifying if checkbox is already selected

We will make use of getAttribute()method to verify if a checkbox is already selected or not. We have observed in above figure that for any checked option, the attribute is “checked”. This is same as we have used in Radio Button tutorial.

WebElement checkBoxIsSelected = driver.findElement(By.name("option1"));
        if(checkBoxIsSelected.getAttribute("checked") == null) {
            System.out.println("Not Checked");
        }else {
            System.out.println("Checked");
        }

In above example, we are storing the reference of checkbox with name “option1″(Milk) to variable checkBoxIsSelected, which is of type WebElement(Remember, findElement() and findElements() method always return WebElement and List of WebElement respectively.)

In all above examples, we have operated on check boxes which have different name attribute. Now lets proceed to our lab exercise which will give you a glimpse of actual operations performed on check boxes.

Lab Exercise:

Write a Selenium script to perform following test:

  1. Navigate to AUT http://www.tizag.com/htmlT/htmlcheckboxes.php
  2. Select Soccer and Baseball checkboxes under HTML Checkbox Form section.
  3. Verify if Soccer checkbox is checked.

Following is the screen shot of Inspect Element of our AUT:

Handling check box in Selenium

It is evident from above figure, name attribute is same (“sports”) for all the check boxes under HTML Checkbox Form section, hence we can make use offindElements()method to get reference of this section and then we can traverse all the check box WebElements under this section.

1. Navigate to AUT http://www.tizag.com/htmlT/htmlcheckboxes.php

Please refer to Navigating Between Windows using Selenium for the code to launch a website. We will create a method which will open the test url.

public void getUrl() {
        System.setProperty("webdriver.chrome.driver", "E:chromedriver_2.43chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized"); // open Browser in maximized mode
        options.addArguments("disable-infobars"); // disabling infobars
        options.addArguments("--disable-extensions"); // disabling extensions
        options.addArguments("--disable-gpu"); // applicable to windows os only
        options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
        options.addArguments("--no-sandbox"); // Bypass OS security model
        driver = new ChromeDriver(options);
        driver.get("http://www.tizag.com/htmlT/htmlcheckboxes.php");
}

2. Select Soccer and Baseball checkboxes under HTML Checkbox Form section.Using Inspect Element, we have seen that the class containing these check boxes is “display”. We will take reference of this class and store it in some variable.

    public void getReference() {
        WebElement tableReference = driver.findElement(By.cssSelector(".display"));
    }

We have saved the reference of section containing all these check boxes into tableReferencevariable of type WebElement. Now we will use findElements()to get all the check boxes reference. Once we have references stored in some List, we can print the values using getAttribute(“value”)method, where “value” is the keyword used to denote the value of check box(refer above screen shot).

public void getReference() {
        WebElement tableReference = driver.findElement(By.cssSelector(".display"));
        List<WebElement> checkboxRef = tableReference.findElements(By.name("sports"));
        for (WebElement ref : checkboxRef) {
            if(ref.getAttribute("value").contains("soccer")||ref.getAttribute("value").contains("baseball")) {
                ref.click();
            }
            
        }
    }

3. Verify if Soccer checkbox is checked.We will create another method, which will take the reference of section containing all the check boxes and then will verify the getAttribute(“checked”)method to verify if  “Soccer” is checked or not.

    public void verifySoccerIsChecked() {
        WebElement tableReference = driver.findElement(By.cssSelector(".display"));
        List<WebElement> checkboxRef = tableReference.findElements(By.name("sports"));
        for (WebElement ref : checkboxRef) {
            if(ref.getAttribute("value").contains("soccer")) {
                if(ref.getAttribute("checked")!=null) {
                    System.out.println("Checked");
                }
            }
            
        }
    }
Full Code is written below:
package testpkg;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class CheckboxDemo {

    public WebDriver driver;

    public static void main(String[] args) {
        CheckboxDemo obj = new CheckboxDemo();
        obj.getUrl();
        obj.getReference();
        obj.verifySoccerIsChecked();

    }

    public void getUrl() {
        System.setProperty("webdriver.chrome.driver", "E:chromedriver_2.43chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized"); // open Browser in maximized mode
        options.addArguments("disable-infobars"); // disabling infobars
        options.addArguments("--disable-extensions"); // disabling extensions
        options.addArguments("--disable-gpu"); // applicable to windows os only
        options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
        options.addArguments("--no-sandbox"); // Bypass OS security model
        driver = new ChromeDriver(options);
        driver.get("http://www.tizag.com/htmlT/htmlcheckboxes.php");

    }

    public void getReference() {
        WebElement tableReference = driver.findElement(By.cssSelector(".display"));
        List<WebElement> checkboxRef = tableReference.findElements(By.name("sports"));
        for (WebElement ref : checkboxRef) {
            if (ref.getAttribute("value").contains("soccer") || ref.getAttribute("value").contains("baseball")) {
                ref.click();
            }

        }
    }

    public void verifySoccerIsChecked() {
        WebElement tableReference = driver.findElement(By.cssSelector(".display"));
        List<WebElement> checkboxRef = tableReference.findElements(By.name("sports"));
        for (WebElement ref : checkboxRef) {
            if (ref.getAttribute("value").contains("soccer")) {
                if (ref.getAttribute("checked") != null) {
                    System.out.println("Checked");
                }
            }

        }
    }

}

Try to perform the exercise on various websites, and if you feel any difficulty or query please make use of following comment section and I’ll try to resolve it at earliest.
Thank you for Reading!!!

Author: Dhawal Joshi

A post-graduate in MCA, ISTQB & ITIL certified QA with more than 8 years of experience in QA working with a CMMI Level 5 organization as System Analyst. I started my automation journey with HP UFT(formerly known as QTP) and for the past few years, I am using Selenium for automation. I also have experience in Android Application Development, Java, HTML, and VBScript. When I am not working, I like to spend time with my family, cooking and learning new developments in IT.

Leave a Reply

Your email address will not be published. Required fields are marked *