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.
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.
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.
Kuldeep is the founder and lead author of ArtOfTesting. He is skilled in test automation, performance testing, big data, and CI-CD. He brings his decade of experience to his current role where he is dedicated to educating the QA professionals. You can connect with him on LinkedIn.
2 thoughts on “Check a checkbox if not already checked”
Nice Implimentation, And I hope this will helpful to lot of students who are learning for selenium and practicing selenium
How to get the count of checkboxes selected in selenium with python