Handling checkbox using Selenium WebDriver with Java

Handling Checkbox using Selenium WebDriver with Java is pretty much similar to handling radio buttons.

The only difference between Checkbox and Radio button is that we can choose multiple checkbox values at a time, but that is not the case with radio button.

Get the list of checkboxes :

List<WebElement> colorCheckboxList = driver.findElements(By.name(“color”));

Get total number of checkboxes :

System.out.println(“Total no of checkboxes ” + colorCheckboxList.size());

Get the particular checkbox by INDEX :

WebElement firstCheckbox = colorCheckboxList.get(0);

WebElement secondCheckbox = colorCheckboxList.get(1);

Get the particular checkbox by VALUE :

WebElement orangeCheckbox;

for (WebElement checkbox : colorCheckboxList) {

if (checkbox.getAttribute(“value”).equalsIgnoreCase(“orange”){

orangeCheckbox = checkbox;

}

}

Get the status of all checkboxes :

for (WebElement checkbox : colorCheckboxList) {

               System.out.println(“Checkbox ” + checkbox.getAttribute(“value”) + ” is selected : ” +                    checkbox.isSelected());

}

Select the Checkbox :

System.out.println(“Selecting the second checkbox  “);

colorCheckboxList.get(1).click();

Let’ have a look at below snippet to see the code in action.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CheckBox {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http://www.ironspider.ca/forms/checkradio.htm”);

List<WebElement> colorCheckboxList = driver.findElements(By.name(“color”));

System.out.println(“Total no of checkboxes ” + colorCheckboxList.size());

for (WebElement checkbox : colorCheckboxList) {
if (checkbox.getAttribute(“value”).equalsIgnoreCase(“orange”)
|| checkbox.getAttribute(“value”).equalsIgnoreCase(“yellow”)) {
checkbox.click();
}

System.out.println(“Checkbox ” + checkbox.getAttribute(“value”)
+ ” is selected : ” + checkbox.isSelected());
}

driver.quit();
}
}

Hope it helps you !!

Cheers 🙂

 

Advertisements

#get-status-of-checkbox-in-webdriver, #handling-checkbox-in-webdriver