How can I select checkboxes using the Selenium Java WebDriver? How can I select checkboxes using the Selenium Java WebDriver? selenium selenium

How can I select checkboxes using the Selenium Java WebDriver?


Selecting a checkbox is similar to clicking a button.

driver.findElement(By.id("idOfTheElement")).click();

will do.

However, you can also see whether the checkbox is already checked. The following snippet checks whether the checkbox is selected or not. If it is not selected, then it selects.

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() ){     driver.findElement(By.id("idOfTheElement")).click();}


It appears that the Internet Explorer driver does not interact with everything in the same way the other drivers do and checkboxes is one of those cases.

The trick with checkboxes is to send the Space key instead of using a click (only needed on Internet Explorer), like so in C#:

if (driver.Capabilities.BrowserName.Equals(“internet explorer"))    driver.findElement(By.id("idOfTheElement").SendKeys(Keys.Space);else    driver.findElement(By.id("idOfTheElement").Click();


If you want to click on all checkboxes at once, a method like this will do:

private void ClickAllCheckboxes(){    foreach (IWebElement e in driver.FindElements(By.xpath("//input[@type='checkbox']")))    {        if(!e.Selected)            e.Click();    }}