How to Handle Checkbox in Selenium | Selenium WebDriver

Опубликовано: 10 Октябрь 2023
на канале: Selenium Java
8
1

Handling checkboxes in Selenium is a common task
1)Locate the Checkbox Element:
First, you need to locate the checkbox element on the web page using one of the available locators such as id, name, xpath, cssSelector, etc. For example, to locate a checkbox by its id:
WebElement checkbox = driver.findElement(By.id("checkboxId"));

2)Check the Checkbox:
To check (select) a checkbox, you can use the click() method on the checkbox
checkbox.click();

3)Uncheck the Checkbox:
To uncheck (deselect) a checkbox, you can use the click() method again. Toggling the state will uncheck the checkbox if it's already checked:
checkbox.click();

4)Verify Checkbox State:
You can use the isSelected() method to check whether a checkbox is currently checked or unchecked. It returns a boolean value indicating the checkbox's state:
boolean isChecked = checkbox.isSelected();

5)If you r working with multiplecheckbox on a page, you can use a loop to iterate through them and perform actions as needed. checking all checkboxes with a specific class:

List (WebElement )checkboxes = driver.findElements(By.className("checkboxClass"));
for (WebElement checkbox : checkboxes) {
checkbox.click();
}