How to handle multiple Check Boxes in Selenium WebDriver?

A group of check boxes is created by giving two or more checkboxes the same control name. In the above example, the checkbox group control name is “color”. However, each checkbox in the group has a different associated value specified by the value attribute.

When a user selects (checks) a checkbox, its value gets assigned as the current value of the checkbox group’s control name. A checkbox group’s control name may conceivably get paired with several current values if the user selects more than one checkbox.
Let us consider below screen which show the example of check boxes.
 
Source code for check boxes shown in above image is:
My favourite colors are:<br><br>
<input type="checkbox" name="color" value="red">
Red<br>
<input type="checkbox" name="color" value="yellow">
Yellow<br>
<input type="checkbox" name="color" value="blue">
Blue<br>
<input type="checkbox" name="color" value="orange">
Orange<br>
<input type="checkbox" name="color" value="green">
Green<br>
<input type="checkbox" name="color" value="purple"> 
Purple<br>

By observing above HTML code, we can see that, name of all the check boxes is same. So what we can do is, get the list of all check boxes by using attribute name and iterate over it. If found matching, then click on it.

Below piece of code illustrate the same. –

package learnAboutActionsClass;

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

 public static void main(String[] args) {

  
  WebDriver driver = new FirefoxDriver();
  
  driver.navigate().to("http://www.ironspider.ca/forms/checkradio.htm");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  List<WebElement> ListOfCheckBoxes = driver.findElements(By.name("color"));
  System.out.println("Number of check boxes pesent are: "+ListOfCheckBoxes.size());
  
  for(int i=0; i< ListOfCheckBoxes.size() ; i++) {
   if(ListOfCheckBoxes.get(i).getAttribute("value").equalsIgnoreCase("Red")){
    ListOfCheckBoxes.get(i).click();
   }
       }
  
 }

}

Refer below video for same explanation –

 

Refer below post for complete example of Automation of Registration page using Selenium WebDriver.
Hope this Helps!!!

Leave Comment

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

Looking for learning Framework Development from Scratch? Lookout for Detailed Framework Development videos on YouTube here -

https://www.youtube.com/automationtalks

Get the Framework code at Github Repo: https://github.com/prakashnarkhede?tab=repositories