9t. WebDriver – Handling radio buttons and checkboxes

Hiya superstars! I know that you are now an expert in handling text boxes and images, but there is more to learn. Let us get hard-core! Let us understand how to handle radio buttons, checkboxes, dropdowns, tables, alerts and much more but we will see one at a time. In this post, we will concentrate on handling radio buttons and checkboxes. At the end, you will be more expressive with WebDriver than you ever thought is possible.

Prepare to be lit up

Radio Buttons: In a group of radio buttons, only one can be selected at a time. In HTML, they are represented using <input> tag with type attribute as ‘radio’.

Checkboxes: In a group of checkboxes, each one operates individually and user can select multiple checkboxes as per the requirement. In HTML, checkbox is represented using <input> tag with type attribute as ‘checkbox’.

Now that we have some clarity on how radio buttons and checkboxes work, lets have some fun manipulating them using Selenium WebDriver.

  1. Locating a radio button and checkbox using various locating strategies
  2. Checking if a radio button/checkbox is displayed [HINT: isDisplayed() method]
  3. Checking if a radio button/checkbox is enabled so that it can be selected [HINT: isEnabled() method]
  4. Checking if a radio button/checkbox is selected by default [HINT: isSelected() method]
  5. Selecting/clicking the radio button or checkbox [HINT: click()]

These five actions will be explained along with examples from our demo site. It doesn’t have the best UI in the world but it serves the purpose for now.

1. Locating a radio button and checkbox using various locating strategies

Time to harness the power of locating strategies one more time!

Example: Let us locate ‘Bicycle’ checkbox by id, ‘Tricycle’ checkbox by name, ‘Sedan’ checkbox by xPath and ‘Magazines’ radio button by cssSelector.

Right clicking on required elements and selecting inspect element gives corresponding HTML code which is as below,

<input id="bicycle-checkbox" type="checkbox" name="vehicle1" value="Bicycle">&nbsp;Bicycle  
<input id="tricycle-checkbox" type="checkbox" name="vehicle2" value="Tricycle" disabled>&nbsp;Tricycle
<input id="sedan-checkbox" type="checkbox" name="vehicle5" value="Sedan">&nbsp;Sedan
<input id="magazines-radio-btn" type="radio" name="books" value="Magazines"> &nbsp;Magazines

Code:

driver.findElement(By.id("bicycle-checkbox"));
driver.findElement(By.name("vehicle2"));
driver.findElement(By.xpath("//input[@name='vehicle5']"));
driver.findElement(By.cssSelector("input[value='Magazines']"));

2. Checking if a radio button/checkbox is displayed

With Selenium WebDriver, checking if a particular radio button or checkbox is displayed on the web page as expected, is a piece of cake! We have isDisplayed() method to our rescue. This method returns a boolean value (true – element is displayed and false – element is not displayed).

Example: Let us check if the located ‘Tricycle’ checkbox is displayed on the web page.

Respective HTML code for reference,

<input id="tricycle-checkbox" type="checkbox" name="vehicle2" value="Tricycle" disabled>&nbsp;Tricycle

Code:

driver.findElement(By.name("vehicle2")).isDisplayed();

3. Checking if a radio button/checkbox is enabled so that it can be selected

Similarly, in order to verify if a particular radio button or checkbox is enabled on not, we have isEnabled() method. This also returns a boolean value (true – element is enabled and false – element is disabled).

Example: Let us check if the located ‘Tricycle’ checkbox is enabled. If yes, let us check it otherwise we will just print a message to the console.

Respective HTML code for reference,

<input id="tricycle-checkbox" type="checkbox" name="vehicle2" value="Tricycle" disabled>&nbsp;Tricycle

Code:

WebElement tricycleCheckbox = driver.findElement(By.name("vehicle2"));
// Check if tricyle is enabled to select
if (tricycleCheckbox.isEnabled()) {
// Click if enabled
	tricycleCheckbox.click();
} else {
	// Print message to console if disabled
	System.out.println("Unable to select 'Tricycle' checkbox as it is disabled.");
}

4. Checking if a radio button/checkbox is selected by default

To verify if a particular radio button or checkbox is selected by defaulted, we have isSelected() method. This also returns a boolean value (true – element is selected and false – element is not selected).

Example: Let us check if the located ‘Magazines’ radio button is selected by default. If yes, let us print that message to the console otherwise we will click on it to select Magazines option.

Respective HTML code for reference,

<input id="magazines-radio-btn" type="radio" name="books" value="Magazines"> &nbsp;Magazines

Code:

// Locate 'Magazines' radio button using cssSelector
WebElement magazinesRadioBtn = driver.findElement(By
				.cssSelector("input[value='Magazines']"));
// Check if radio button is selected by default
if (magazinesRadioBtn.isSelected()) {
        // Print message to console
	System.out.println("Magazines radio button is selected by default");
} else {
	// Click the radio button
	magazinesRadioBtn.click();
}

5. Selecting/clicking the radio button or checkbox

Why do you think we have click() in Selenium WebDriver? You got me! It is that easy to select a radio button and in the case of checkboxes, same click() can be used to toggle between check and uncheck!!

Example: Let us check and uncheck the ‘Sedan’ checkbox.

Respective HTML code for reference,

<input id="sedan-checkbox" type="checkbox" name="vehicle5" value="Sedan">&nbsp;Sedan

Code:

// Locate 'Sedan' checkbox using xPath: contains() and text()
WebElement sedanCheckbox = driver.findElement(By.xpath("//input[@name='vehicle5']"));
for (int i = 0; i < 2; i++) {
// Click the checkbox
	sedanCheckbox.click();
	// Print current status to console
	System.out.println("Selection status of 'Sedan' checkbox: "
					+ sedanCheckbox.isSelected());
}

This code will check the ‘Sedan’ checkbox on the first iteration and then uncheck it on the second iteration. Selection status messages will be printed accordingly to the console.

Overall picture

Let us see a test case implementing all the actions covered in this post so far,

Scenario

  1. Open Firefox browser.
  2. Navigate to the demo site
  3. Locate ‘Tricycle’ checkbox by name
  4. Check if the ‘Tricycle’ checkbox is displayed and print the corresponding message to console
  5. Check if the ‘Tricycle’ checkbox is enabled
  6. If yes, click on the checkbox and if no, print corresponding message to console
  7. Based on the current selection status of ‘Van’ and ‘SUV’ checkboxes, check or uncheck and print the status before and after performing click() action
  8. Locate ‘Sedan’ checkbox using XPath
  9. Toggle between select and unselect states using two iterations
  10. Locate ‘Magazines’ radio button using cssSelector
  11. Check if it is selected by default
  12. If yes, print corresponding message to console and if no, select the radio button
  13. Verify Eclipse IDE console output screen and JUnit pane for success result

JUnit code for this scenario is,

package com.blog.junitTests;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class RadioBtns_Checkboxes {
    // Declaring variables
    private WebDriver driver;
    private String baseUrl;

    @Before
    public void setUp() throws Exception {
        // Selenium version 3 beta releases require system property set up
        System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\
Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
        // Create a new instance for the class FirefoxDriver
        // that implements WebDriver interface
        driver = new FirefoxDriver();
        // Implicit wait for 5 seconds
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        // Assign the URL to be invoked to a String variable
        baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";
    }

    @Test
    public void testPageTitle() throws Exception {
        // Open baseUrl in Firefox browser window
        driver.get(baseUrl);

        // Locate 'Tricycle' checkbox using name
        WebElement tricycleCheckbox = driver.findElement(By.name("vehicle2"));
        // Check if tricyle is displayed
        System.out.println("Is tricycle displayed? "+ tricycleCheckbox.isDisplayed());
        
        // Check if tricyle is enabled to select
        if (tricycleCheckbox.isEnabled()) {
            // Click if enabled
            tricycleCheckbox.click();
        } else {
            // Print message to console if disabled
            System.out.println("Unable to select 'Tricycle' checkbox as it is disabled.");
        }
        
        //Get all checkbox elements in a list
        List<WebElement> list = driver.findElements(By
                .cssSelector("input[type='checkbox']"));

        // Loops through all checkboxe elements
        for (int i = 0; i < list.size(); i++) {
            // Checking if the checkbox is a 'Van' or 'SUV'
            if ((list.get(i).getAttribute("value").trim()
                    .equalsIgnoreCase("van"))
                    || (list.get(i).getAttribute("value").trim()
                            .equalsIgnoreCase("suv"))) {
                // Print selection status to console
                System.out.println("BEFORE: Is "
                        + list.get(i).getAttribute("value") + " selected? "
                        + list.get(i).isSelected());
                // Check if the checkbox is selected
                if (!(list.get(i).isSelected())) {
                    // Click the checkbox
                    list.get(i).click();
                    System.out.println("AFTER: Is "
                            + list.get(i).getAttribute("value") + " selected? "
                            + list.get(i).isSelected());
                } else {
                    // Uncheck the checkbox
                    list.get(i).click();
                    System.out.println("AFTER: Is "
                            + list.get(i).getAttribute("value") + " selected? "
                            + list.get(i).isSelected());
                }
                System.out.println("Next...");
            }
        }
        // Locate 'Sedan' checkbox using xPath
        WebElement sedanCheckbox = driver.findElement(By
                .xpath("//input[@name='vehicle5']"));
        System.out.println("Trying to select and de-select Sedan checkbox...");
        for (int i = 0; i < 2; i++) {
            // Click the checkbox
            sedanCheckbox.click();
            // Print current status to console
            System.out.println("Selection status of 'Sedan' checkbox: "
                    + sedanCheckbox.isSelected());
        }
        // Locate 'Magazines' radio button using cssSelector
        WebElement magazinesRadioBtn = driver.findElement(By
                .cssSelector("input[value='Magazines']"));
        // Check if radio button is selected by default
        if (magazinesRadioBtn.isSelected()) {
            // Print message to console
            System.out.println("Magazines radio button is selected by default");
        } else {
            // Click the radio button
            magazinesRadioBtn.click();
        }
        
    } //End of @Test

    @After
    public void tearDown() throws Exception {
        // Close the Firefox browser
        driver.close();
    }
}

Execution Result:

Parts of the code are explained as part of each technique discussed in this post except for one snippet.

All web elements of type checkbox are obtained in a list,

//Get all checkbox elements in a list
List<WebElement> list = driver.findElements(By.cssSelector("input[type='checkbox']"));

All the checkbox elements in the list are verified if they have an attribute value that matches ‘Van’ and ‘SUV’. Their current selection status is printed to console as a message saying, BEFORE.

// Loops through all checkboxe elements
for (int i = 0; i < list.size(); i++) {
	// Checking if the checkbox is a 'Van' or 'SUV'
	if ((list.get(i).getAttribute("value").trim().equalsIgnoreCase("van"))
||(list.get(i).getAttribute("value").trim().equalsIgnoreCase("suv"))) 
{
		// Print selection status to console
		System.out.println("BEFORE: Is "
			+ list.get(i).getAttribute("value") + " selected? "
				+ list.get(i).isSelected());

Using isSelected() method, check if ‘Van’ or ‘SUV’ checkboxes are selected. Select the checkboxes if they are not selected and print its selection status to console saying AFTER. In case they are already selected,  then deselect them by clicking again and print the corresponding message to console.

// Check if the checkbox is selected
if (!(list.get(i).isSelected())) {
// Click the checkbox								         list.get(i).click();
System.out.println("AFTER: Is "+ list.get(i).getAttribute("value") + " selected? "+ list.get(i).isSelected());
} else {
	// Uncheck the checkbox
	list.get(i).click();
	System.out.println("AFTER: Is "+ list.get(i).getAttribute("value") + " selected? "+ list.get(i).isSelected());
			}
	System.out.println("Next...");
	}
}

In JUnit window, green bar shows that the test case is executed successfully. Console window shows the absence of any errors. It also shows all the printed messages as expected.

Checkbox output IDE

Below image shows the Firefox output obtained upon successful execution of the test script.

Radio Buttons Output Browser

Time to experiment today’s skills. And yes, put on your safety helmets so that you don’t bump into any exceptions!

See you in another post. Have a great day!

1 Comment 9t. WebDriver – Handling radio buttons and checkboxes

  1. savithri

    Hi,
    I got this error always, i am unable to click the check box. For this Capabilities error on previous page, but its gone to next page but i cant click the checkbox. could you please advise me to sort out this issue.

    org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element … is not clickable at point (759, 510). Other element would receive the click: …
    Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 75.0.3770.100, chrome: {chromedriverVersion: 75.0.3770.90 (a6dcaf7e3ec6f…, userDataDir: C:\Users\YOGANA~1\AppData\L…}, goog:chromeOptions: {debuggerAddress: localhost:60416}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true.

    Reply

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.