Check a checkbox if not already checked

Check a checkbox if not already checked

In this post, we will learn how to check if a checkbox is in a checked or unchecked state. Also, we will see how to check/set a checkbox if it is not already checked.

Verify if a checkbox is checked or not

In order to check if a checkbox is checked or unchecked, we can used the isSelected() method over the checkbox element. The isSelected() method returns a boolean value of true if the checkbox is checked false otherwise.

Code Snippet

WebElement checkbox = driver.findElement(By.id("checkboxId"));
System.out.println("The checkbox is selection state is - " + checkbox.isSelected());

Check a checkbox if not already checked

During automation, if we want to check a checkbox with click() method then the checkbox gets unchecked if its already checked. So, if you want to make sure that you are only checking the checkbox then we should first get the checkbox state using isSelected() method and then click on it only if it is in unchecked state.

Code Snippet

WebElement checkbox = driver.findElement(By.id("checkboxId"));
//If the checkbox is unchecked then isSelected() will return false
//and NOT of false is true, hence we can click on checkbox
if(!checkbox.isSelected())
checkbox.click();

Check our complete step-by-step selenium tutorial here.

Selenium with Java – Complete Tutorial

От QA genius

Adblock
detector