Selenium WebDriver supports the
checkbox element using the WebElement
interface. We can select or deselect a checkbox using the click()
method and check whether a checkbox is selected or deselected using the isSelected()
method.
In this recipe, we will see how to work with the checkbox element.
Here is the code for a test that has a checkbox and performs the select and deselect operations:
@Test public void testCheckBox() { //Get the Checkbox as WebElement using it's value attribute WebElement airbags = driver.findElement(By.xpath("//input[@value='Airbags']")); //Check if its already selected? otherwise select the Checkbox //by calling click() method if (!airbags.isSelected()) { airbags.click(); } //Verify Checkbox is Selected assertTrue(airbags.isSelected()); //Check Checkbox if selected? If yes, deselect it //by calling click() method if (airbags.isSelected()) { airbags.click(); } //Verify Checkbox is Deselected assertFalse(airbags.isSelected()); }
We can locate a checkbox in a way similar to locating any other element on a page. In this example, XPath is used to locate the checkbox by its value
attribute:
WebElement airbags = driver.findElement(By.xpath("//input[@value='Airbags']"));
We can select or deselect a checkbox by using the click()
method. There are no separate methods to perform these operations. When we want to select a checkbox, we need to be careful that it's not already selected, otherwise calling the click()
method will deselect the checkbox. We can check if a checkbox is already selected by calling the isSelected()
method, which returns true
if it's selected and false
if it's not selected. Here, the click()
method will be called only when the checkbox is not selected:
if (!airbags.isSelected()) { airbags.click(); }
Similarly, to deselect the checkbox, we need to see if it is already selected:
if (airbags.isSelected()) { airbags.click(); }
3.142.133.180