Skip to content

Instantly share code, notes, and snippets.

@SarahElson
Created June 20, 2022 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SarahElson/6a47ddc0453905e46a573e23ec897c54 to your computer and use it in GitHub Desktop.
Save SarahElson/6a47ddc0453905e46a573e23ec897c54 to your computer and use it in GitHub Desktop.
How to select multiple checkboxes in Selenium WebDriver using Java?
package test;
import java.util.List;
import org.openqa.Selenium.By;
import org.openqa.Selenium.WebElement;
import org.testng.annotations.Test;
public class TestCheckboxes extends BaseClass{
@Test
public void testSingleCheckbox()
{
System.out.println("Navigating to the URL");
driver.get("https://www.lambdatest.com/Selenium-playground/checkbox-demo");
//using ID attribute to locate checkbox
WebElement checkbox = driver.findElement(By.id("isAgeSelected"));
//pre-validation to confirm that checkbox is displayed.
if(checkbox.isDisplayed())
{
System.out.println("Checkbox is displayed. Clicking on it now");
checkbox.click();
}
//post-validation to confirm that checkbox is selected.
if(checkbox.isSelected())
{
System.out.println("Checkbox is checked");
}
}
@Test
public void testMultipleCheckbox()
{
System.out.println("Navigating to the URL");
driver.get("https://www.lambdatest.com/Selenium-playground/checkbox-demo");
//using class name to fetch the group of multiple checkboxes
List<WebElement> checkboxes = driver.findElements(By.className("cb-element mr-10"));
//traverse through the list and select all checkboxes if they are enabled and displayed.
for(int i=0; i<checkboxes.size(); i++)
{
if(checkboxes.get(i).isDisplayed() && checkboxes.get(i).isEnabled())
{
System.out.println("Checkbox is displayed at index : " + i + " Clicking on it now");
checkboxes.get(i).click();
}
}
//deselect the checkbox on index 1 from the list of checkboxes selected above
System.out.println("de-selecting checkbox with index 1");
checkboxes.get(1).click();
if(checkboxes.get(1).isSelected())
{
System.out.println("Checkbox is still selected");
}
else
{
System.out.println("Checkbox is deselected successfully");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment