<div class="selenium-notes">
<h1>Checkboxes in Selenium</h1>
<p>Checkboxes are common web elements used in web applications to allow users to select one or more options independently. In Selenium WebDriver, checkboxes can be located and interacted with using methods such as <code>click()</code>, <code>isSelected()</code>, <code>isDisplayed()</code>, and <code>isEnabled()</code>.</p>
<p>Checkbox automation is an important part of form testing because testers need to verify whether a checkbox can be selected, deselected, enabled, disabled, displayed correctly, and handled according to the application's business rules.</p>
<p>Checkbox handling is also included within Selenium training topics related to WebElements and form interactions. <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Learn more about Selenium Training</a> and <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for a Course Demo</a>.</p>
<hr>
<h2>1. What is a Checkbox?</h2>
<p>A checkbox is an HTML form control that allows a user to select or deselect an option. Unlike radio buttons, multiple checkboxes can normally be selected at the same time.</p>
<pre><code><input type="checkbox" id="terms">
<label for="terms">I agree to the Terms and Conditions</label></code></pre>
<p>In this example, the checkbox is represented by the <code><input></code> element with <code>type="checkbox"</code>.</p>
<hr>
<h2>2. Why Checkboxes are Important in Automation Testing</h2>
<p>Checkboxes frequently appear in registration forms, checkout pages, filters, settings pages, surveys, preference screens, permissions, and terms-and-conditions sections.</p>
<ul>
<li>Selecting terms and conditions</li>
<li>Choosing product filters</li>
<li>Selecting notification preferences</li>
<li>Enabling account settings</li>
<li>Selecting multiple products</li>
<li>Choosing user permissions</li>
<li>Selecting communication preferences</li>
<li>Testing form validation</li>
</ul>
<hr>
<h2>3. Basic HTML Structure of a Checkbox</h2>
<pre><code><input type="checkbox" id="subscribe" name="subscribe" value="yes">
<label for="subscribe">Subscribe to Newsletter</label></code></pre>
<p>Important attributes include:</p>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Attribute</th><th>Purpose</th></tr>
<tr><td>type</td><td>Defines the input as a checkbox.</td></tr>
<tr><td>id</td><td>Provides a unique identifier.</td></tr>
<tr><td>name</td><td>Identifies the form field.</td></tr>
<tr><td>value</td><td>Stores the value submitted with the form.</td></tr>
<tr><td>class</td><td>Provides CSS-based identification or styling.</td></tr>
<tr><td>checked</td><td>Indicates that the checkbox is selected by default.</td></tr>
<tr><td>disabled</td><td>Prevents user interaction.</td></tr>
</table>
<hr>
<h2>4. Checkbox Types in Web Applications</h2>
<ul>
<li>Single checkbox</li>
<li>Multiple independent checkboxes</li>
<li>Pre-selected checkbox</li>
<li>Disabled checkbox</li>
<li>Dynamic checkbox</li>
<li>Custom styled checkbox</li>
<li>Checkbox inside a table</li>
<li>Checkbox inside a modal</li>
<li>Checkbox inside an iframe</li>
<li>Select All checkbox</li>
<li>Indeterminate checkbox</li>
</ul>
<hr>
<h2>5. Setting Up Selenium for Checkbox Testing</h2>
<p>The following Java example demonstrates a basic Selenium setup.</p>
<pre><code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CheckboxTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.quit();
}
}</code></pre>
<hr>
<h2>6. Locating a Checkbox Using ID</h2>
<p>If a checkbox has a unique ID, the ID locator is generally straightforward to use.</p>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
checkbox.click();</code></pre>
<hr>
<h2>7. Locating a Checkbox Using Name</h2>
<pre><code>WebElement checkbox = driver.findElement(By.name("subscribe"));
checkbox.click();</code></pre>
<hr>
<h2>8. Locating a Checkbox Using Class Name</h2>
<pre><code>WebElement checkbox = driver.findElement(By.className("checkbox-input"));
checkbox.click();</code></pre>
<p>Class Name should be used carefully when multiple elements have the same class.</p>
<hr>
<h2>9. Locating a Checkbox Using Tag Name</h2>
<pre><code>WebElement checkbox = driver.findElement(By.tagName("input"));
checkbox.click();</code></pre>
<p>Using only <code>input</code> may locate the wrong element when a page contains multiple input fields.</p>
<hr>
<h2>10. Locating a Checkbox Using CSS Selector</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.cssSelector("input[type='checkbox']")
);
checkbox.click();</code></pre>
<p>CSS selectors are useful when the checkbox does not have a convenient unique ID.</p>
<hr>
<h2>11. CSS Selector Using ID</h2>
<pre><code>WebElement checkbox = driver.findElement(By.cssSelector("#terms"));
checkbox.click();</code></pre>
<hr>
<h2>12. CSS Selector Using Class</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.cssSelector(".checkbox-input")
);
checkbox.click();</code></pre>
<hr>
<h2>13. CSS Selector Using Attribute</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.cssSelector("input[type='checkbox']")
);
checkbox.click();</code></pre>
<hr>
<h2>14. CSS Selector Combining Attributes</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.cssSelector("input[type='checkbox'][name='subscribe']")
);
checkbox.click();</code></pre>
<hr>
<h2>15. Locating Checkbox Using XPath</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//input[@type='checkbox']")
);
checkbox.click();</code></pre>
<hr>
<h2>16. XPath Using ID</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//input[@id='terms']")
);
checkbox.click();</code></pre>
<hr>
<h2>17. XPath Using Name</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//input[@name='subscribe']")
);
checkbox.click();</code></pre>
<hr>
<h2>18. XPath Using Multiple Attributes</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//input[@type='checkbox' and @name='subscribe']")
);
checkbox.click();</code></pre>
<hr>
<h2>19. XPath Using Label Text</h2>
<p>Sometimes the checkbox itself does not have a useful locator, but its associated label contains meaningful text.</p>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//label[normalize-space()='Subscribe to Newsletter']/preceding-sibling::input")
);
checkbox.click();</code></pre>
<hr>
<h2>20. The click() Method</h2>
<p>The <code>click()</code> method is used to select or deselect a checkbox.</p>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
checkbox.click();</code></pre>
<p>If the checkbox is unchecked, clicking it normally selects it. If it is already selected, clicking it normally deselects it.</p>
<hr>
<h2>21. Understanding isSelected()</h2>
<p>The <code>isSelected()</code> method checks whether a checkbox is currently selected.</p>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (checkbox.isSelected()) {
System.out.println("Checkbox is selected");
} else {
System.out.println("Checkbox is not selected");
}</code></pre>
<hr>
<h2>22. Difference Between click() and isSelected()</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Method</th><th>Purpose</th></tr>
<tr><td>click()</td><td>Performs a click action.</td></tr>
<tr><td>isSelected()</td><td>Checks the current selection state.</td></tr>
<tr><td>isDisplayed()</td><td>Checks whether the checkbox is visible.</td></tr>
<tr><td>isEnabled()</td><td>Checks whether the checkbox is enabled.</td></tr>
</table>
<hr>
<h2>23. Select Checkbox Only If It Is Not Selected</h2>
<p>A common automation requirement is to select a checkbox only when it is currently unchecked.</p>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<p>This approach avoids accidentally deselecting an already selected checkbox.</p>
<hr>
<h2>24. Deselect Checkbox Only If It Is Selected</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<hr>
<h2>25. Verify Checkbox Is Selected</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
checkbox.click();
if (checkbox.isSelected()) {
System.out.println("Checkbox selected successfully");
}</code></pre>
<hr>
<h2>26. Verify Checkbox Is Not Selected</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
System.out.println("Checkbox is not selected");
}</code></pre>
<hr>
<h2>27. Checking Checkbox Visibility</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (checkbox.isDisplayed()) {
System.out.println("Checkbox is visible");
}</code></pre>
<hr>
<h2>28. Checking Checkbox Enabled State</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (checkbox.isEnabled()) {
System.out.println("Checkbox is enabled");
} else {
System.out.println("Checkbox is disabled");
}</code></pre>
<hr>
<h2>29. Complete Checkbox Validation</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
System.out.println("Displayed: " + checkbox.isDisplayed());
System.out.println("Enabled: " + checkbox.isEnabled());
System.out.println("Selected: " + checkbox.isSelected());</code></pre>
<hr>
<h2>30. Multiple Checkboxes</h2>
<p>A page may contain several checkboxes such as multiple product categories.</p>
<pre><code><input type="checkbox" name="skill" value="java"> Java
<input type="checkbox" name="skill" value="selenium"> Selenium
<input type="checkbox" name="skill" value="python"> Python
<input type="checkbox" name="skill" value="sql"> SQL</code></pre>
<hr>
<h2>31. Finding Multiple Checkboxes</h2>
<pre><code>List<WebElement> checkboxes = driver.findElements(
By.cssSelector("input[type='checkbox']")
);</code></pre>
<hr>
<h2>32. Import Required for List</h2>
<pre><code>import java.util.List;</code></pre>
<hr>
<h2>33. Count Number of Checkboxes</h2>
<pre><code>List<WebElement> checkboxes = driver.findElements(
By.cssSelector("input[type='checkbox']")
);
System.out.println("Total checkboxes: " + checkboxes.size());</code></pre>
<hr>
<h2>34. Select All Checkboxes</h2>
<pre><code>List<WebElement> checkboxes = driver.findElements(
By.cssSelector("input[type='checkbox']")
);
for (WebElement checkbox : checkboxes) {
if (!checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>35. Deselect All Checkboxes</h2>
<pre><code>List<WebElement> checkboxes = driver.findElements(
By.cssSelector("input[type='checkbox']")
);
for (WebElement checkbox : checkboxes) {
if (checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>36. Select Specific Checkbox From Multiple Checkboxes</h2>
<pre><code>WebElement seleniumCheckbox = driver.findElement(
By.xpath("//input[@value='selenium']")
);
if (!seleniumCheckbox.isSelected()) {
seleniumCheckbox.click();
}</code></pre>
<hr>
<h2>37. Select Checkbox Based on Label</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//label[normalize-space()='Selenium']/preceding-sibling::input")
);
if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<hr>
<h2>38. Handling Checkbox With Following-Sibling</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//label[normalize-space()='Java']/preceding-sibling::input")
);
checkbox.click();</code></pre>
<hr>
<h2>39. Handling Checkbox With Parent Container</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//div[contains(@class,'skill-option')]//input[@type='checkbox']")
);
checkbox.click();</code></pre>
<hr>
<h2>40. Checkbox With Dynamic ID</h2>
<p>Modern web applications may generate dynamic IDs.</p>
<pre><code><input type="checkbox" id="checkbox_98231"></code></pre>
<p>Instead of depending on the complete dynamic ID, use stable attributes when available.</p>
<pre><code>WebElement checkbox = driver.findElement(
By.cssSelector("input[type='checkbox']")
);</code></pre>
<hr>
<h2>41. XPath contains() for Dynamic Checkbox</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//input[contains(@id,'checkbox_')]")
);</code></pre>
<hr>
<h2>42. XPath starts-with() for Dynamic Checkbox</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//input[starts-with(@id,'checkbox_')]")
);</code></pre>
<hr>
<h2>43. Handling Disabled Checkbox</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("disabledOption"));
if (checkbox.isEnabled()) {
checkbox.click();
} else {
System.out.println("Checkbox is disabled");
}</code></pre>
<p>A disabled checkbox should normally not be clicked because the application intentionally prevents interaction.</p>
<hr>
<h2>44. Handling Pre-Selected Checkbox</h2>
<p>Some checkboxes may already be selected when the page loads.</p>
<pre><code>WebElement checkbox = driver.findElement(By.id("newsletter"));
if (checkbox.isSelected()) {
System.out.println("Checkbox is already selected");
} else {
checkbox.click();
}</code></pre>
<hr>
<h2>45. Checkbox With Label</h2>
<pre><code><input type="checkbox" id="emailAlert">
<label for="emailAlert">Receive Email Alerts</label></code></pre>
<p>When the label is correctly associated with the checkbox, clicking the label may also change the checkbox state.</p>
<hr>
<h2>46. Clicking Label Instead of Checkbox</h2>
<pre><code>WebElement label = driver.findElement(
By.cssSelector("label[for='emailAlert']")
);
label.click();</code></pre>
<p>This technique can be useful when the actual checkbox is hidden or visually replaced by a custom UI component.</p>
<hr>
<h2>47. Custom Styled Checkbox</h2>
<p>Modern websites often hide the native checkbox and use CSS to display a custom checkbox.</p>
<pre><code><input type="checkbox" id="darkMode" hidden>
<label for="darkMode" class="custom-checkbox">
Enable Dark Mode
</label></code></pre>
<p>In such cases, Selenium may need to interact with the associated label rather than the hidden input.</p>
<hr>
<h2>48. Handling Hidden Checkbox</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("darkMode"));
System.out.println(checkbox.isDisplayed());</code></pre>
<p>If the input is hidden, directly calling <code>click()</code> may result in an interaction exception. Identify the visible control or associated label instead.</p>
<hr>
<h2>49. ElementClickInterceptedException</h2>
<p><code>ElementClickInterceptedException</code> can occur when another element is positioned over the checkbox or intercepts the click.</p>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
try {
checkbox.click();
} catch (ElementClickInterceptedException e) {
System.out.println("Checkbox click was intercepted");
}</code></pre>
<hr>
<h2>50. ElementNotInteractableException</h2>
<p>This exception can occur when Selenium finds an element but the element cannot currently be interacted with.</p>
<pre><code>try {
checkbox.click();
} catch (ElementNotInteractableException e) {
System.out.println("Checkbox cannot be interacted with");
}</code></pre>
<hr>
<h2>51. NoSuchElementException</h2>
<p>If Selenium cannot locate the checkbox, <code>NoSuchElementException</code> may occur.</p>
<pre><code>try {
WebElement checkbox = driver.findElement(By.id("terms"));
checkbox.click();
} catch (NoSuchElementException e) {
System.out.println("Checkbox was not found");
}</code></pre>
<hr>
<h2>52. StaleElementReferenceException</h2>
<p>A checkbox reference can become stale when the page dynamically refreshes or the DOM is rebuilt.</p>
<pre><code>try {
WebElement checkbox = driver.findElement(By.id("terms"));
checkbox.click();
} catch (StaleElementReferenceException e) {
System.out.println("Checkbox reference became stale");
}</code></pre>
<hr>
<h2>53. Waiting for Checkbox Visibility</h2>
<p>Dynamic applications may render checkboxes after the initial page load. An explicit wait can help synchronize the test.</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement checkbox = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("terms"))
);</code></pre>
<hr>
<h2>54. Waiting for Checkbox to Become Clickable</h2>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement checkbox = wait.until(
ExpectedConditions.elementToBeClickable(By.id("terms"))
);
checkbox.click();</code></pre>
<hr>
<h2>55. Implicit Wait for Checkbox</h2>
<pre><code>driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
WebElement checkbox = driver.findElement(By.id("terms"));
checkbox.click();</code></pre>
<p>Implicit waits apply globally to element searches.</p>
<hr>
<h2>56. Explicit Wait vs Implicit Wait</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Implicit Wait</th><th>Explicit Wait</th></tr>
<tr><td>Applies globally.</td><td>Applies to a specific condition.</td></tr>
<tr><td>Useful for general element searching.</td><td>Useful for dynamic conditions.</td></tr>
<tr><td>Configured once.</td><td>Configured for specific operations.</td></tr>
<tr><td>Less condition-specific.</td><td>More precise.</td></tr>
</table>
<hr>
<h2>57. Selecting Checkboxes With JavaScript</h2>
<p>JavaScript can sometimes be used when normal Selenium interaction is blocked by a custom UI implementation. It should generally be treated as a fallback because it may bypass normal user interaction behavior.</p>
<pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement checkbox = driver.findElement(By.id("terms"));
js.executeScript("arguments[0].click();", checkbox);</code></pre>
<hr>
<h2>58. JavaScript Checking Checkbox State</h2>
<pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;
Boolean selected = (Boolean) js.executeScript(
"return arguments[0].checked;",
checkbox
);
System.out.println("Selected: " + selected);</code></pre>
<hr>
<h2>59. When Not to Use JavaScript Click</h2>
<ul>
<li>Do not use JavaScript click as the first solution.</li>
<li>First verify the locator.</li>
<li>Check whether the element is visible.</li>
<li>Check whether it is enabled.</li>
<li>Check whether an overlay is blocking it.</li>
<li>Use explicit waits when synchronization is the problem.</li>
<li>Use JavaScript only when the application structure requires it.</li>
</ul>
<hr>
<h2>60. Checkbox Inside a Form</h2>
<pre><code><form>
<input type="checkbox" id="terms">
<label for="terms">Accept Terms</label>
<button type="submit">Register</button>
</form></code></pre>
<p>A common test scenario is to verify that registration cannot continue unless the terms checkbox is selected.</p>
<hr>
<h2>61. Testing Mandatory Checkbox</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
WebElement submit = driver.findElement(By.id("register"));
if (!checkbox.isSelected()) {
checkbox.click();
}
submit.click();</code></pre>
<hr>
<h2>62. Testing Terms and Conditions Checkbox</h2>
<pre><code>WebElement terms = driver.findElement(By.id("terms"));
if (!terms.isSelected()) {
terms.click();
}
System.out.println("Terms accepted: " + terms.isSelected());</code></pre>
<hr>
<h2>63. Testing Newsletter Checkbox</h2>
<pre><code>WebElement newsletter = driver.findElement(By.id("newsletter"));
if (!newsletter.isSelected()) {
newsletter.click();
}</code></pre>
<hr>
<h2>64. Testing Product Filter Checkboxes</h2>
<pre><code>List<WebElement> filters = driver.findElements(
By.cssSelector("input[type='checkbox'][name='brand']")
);
for (WebElement filter : filters) {
if (!filter.isSelected()) {
filter.click();
}
}</code></pre>
<hr>
<h2>65. Selecting a Checkbox by Value</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.cssSelector("input[type='checkbox'][value='selenium']")
);
checkbox.click();</code></pre>
<hr>
<h2>66. Selecting Multiple Specific Values</h2>
<pre><code>String[] values = {"java", "selenium", "sql"};
for (String value : values) {
WebElement checkbox = driver.findElement(
By.cssSelector("input[type='checkbox'][value='" + value + "']")
);
if (!checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>67. Select All and Verify</h2>
<pre><code>List<WebElement> checkboxes = driver.findElements(
By.cssSelector("input[type='checkbox']")
);
for (WebElement checkbox : checkboxes) {
if (!checkbox.isSelected()) {
checkbox.click();
}
}
for (WebElement checkbox : checkboxes) {
System.out.println(checkbox.isSelected());
}</code></pre>
<hr>
<h2>68. Count Selected Checkboxes</h2>
<pre><code>List<WebElement> checkboxes = driver.findElements(
By.cssSelector("input[type='checkbox']")
);
int selectedCount = 0;
for (WebElement checkbox : checkboxes) {
if (checkbox.isSelected()) {
selectedCount++;
}
}
System.out.println("Selected checkboxes: " + selectedCount);</code></pre>
<hr>
<h2>69. Count Unselected Checkboxes</h2>
<pre><code>int unselectedCount = 0;
for (WebElement checkbox : checkboxes) {
if (!checkbox.isSelected()) {
unselectedCount++;
}
}
System.out.println("Unselected: " + unselectedCount);</code></pre>
<hr>
<h2>70. Checkbox State Validation With TestNG</h2>
<pre><code>import static org.testng.Assert.assertTrue;
WebElement checkbox = driver.findElement(By.id("terms"));
checkbox.click();
assertTrue(checkbox.isSelected(), "Checkbox should be selected");</code></pre>
<hr>
<h2>71. TestNG Validation for Unselected Checkbox</h2>
<pre><code>import static org.testng.Assert.assertFalse;
WebElement checkbox = driver.findElement(By.id("terms"));
assertFalse(
checkbox.isSelected(),
"Checkbox should not be selected initially"
);</code></pre>
<hr>
<h2>72. Complete TestNG Checkbox Test</h2>
<pre><code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class CheckboxTest {
WebDriver driver;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
driver.get("https://example.com");
}
@Test
public void verifyCheckbox() {
WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}
Assert.assertTrue(
checkbox.isSelected(),
"Checkbox should be selected"
);
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}</code></pre>
<hr>
<h2>73. Checkbox Testing With Page Object Model</h2>
<p>In a Page Object Model framework, checkbox locators and interactions can be maintained inside the page class.</p>
<pre><code>public class RegistrationPage {
private WebDriver driver;
private By termsCheckbox = By.id("terms");
public RegistrationPage(WebDriver driver) {
this.driver = driver;
}
public void acceptTerms() {
WebElement checkbox = driver.findElement(termsCheckbox);
if (!checkbox.isSelected()) {
checkbox.click();
}
}
public boolean isTermsSelected() {
return driver.findElement(termsCheckbox).isSelected();
}
}</code></pre>
<hr>
<h2>74. Reusable Checkbox Utility Method</h2>
<pre><code>public void selectCheckbox(By locator) {
WebElement checkbox = driver.findElement(locator);
if (!checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>75. Reusable Deselect Method</h2>
<pre><code>public void deselectCheckbox(By locator) {
WebElement checkbox = driver.findElement(locator);
if (checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>76. Generic Checkbox State Method</h2>
<pre><code>public boolean isCheckboxSelected(By locator) {
return driver.findElement(locator).isSelected();
}</code></pre>
<hr>
<h2>77. Checkbox Utility With Explicit Wait</h2>
<pre><code>public void selectCheckbox(By locator) {
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement checkbox = wait.until(
ExpectedConditions.elementToBeClickable(locator)
);
if (!checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>78. Checkbox Inside a Table</h2>
<p>Applications often place checkboxes inside tables for selecting records.</p>
<pre><code><table>
<tr>
<td>
<input type="checkbox" name="user" value="101">
</td>
<td>Rahul</td>
</tr>
</table></code></pre>
<hr>
<h2>79. Select Checkbox for a Specific Table Row</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.xpath("//tr[td[normalize-space()='Rahul']]//input[@type='checkbox']")
);
checkbox.click();</code></pre>
<hr>
<h2>80. Checkbox in Product Listing</h2>
<pre><code>WebElement productCheckbox = driver.findElement(
By.xpath("//div[contains(@class,'product')][.//span[normalize-space()='Laptop']]//input[@type='checkbox']")
);
productCheckbox.click();</code></pre>
<hr>
<h2>81. Select All Checkbox</h2>
<p>A Select All checkbox is commonly used to select or deselect a group of checkboxes.</p>
<pre><code>WebElement selectAll = driver.findElement(By.id("selectAll"));
selectAll.click();</code></pre>
<hr>
<h2>82. Verify Select All Behavior</h2>
<pre><code>WebElement selectAll = driver.findElement(By.id("selectAll"));
selectAll.click();
List<WebElement> checkboxes = driver.findElements(
By.cssSelector(".item-checkbox")
);
for (WebElement checkbox : checkboxes) {
System.out.println(checkbox.isSelected());
}</code></pre>
<hr>
<h2>83. Testing Select All and Deselect All</h2>
<ol>
<li>Open the page.</li>
<li>Locate the Select All checkbox.</li>
<li>Click Select All.</li>
<li>Verify every individual checkbox is selected.</li>
<li>Click Select All again.</li>
<li>Verify every individual checkbox is deselected.</li>
</ol>
<hr>
<h2>84. Indeterminate Checkbox</h2>
<p>An indeterminate checkbox represents a partial selection state. It is commonly used when a parent category controls several child checkboxes.</p>
<pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement checkbox = driver.findElement(By.id("parent"));
Boolean indeterminate = (Boolean) js.executeScript(
"return arguments[0].indeterminate;",
checkbox
);
System.out.println("Indeterminate: " + indeterminate);</code></pre>
<hr>
<h2>85. Parent-Child Checkbox Relationship</h2>
<p>Example:</p>
<pre><code>Parent
├── Child 1
├── Child 2
└── Child 3</code></pre>
<p>If all child options are selected, the parent checkbox may become selected. If only some children are selected, the parent may become indeterminate.</p>
<hr>
<h2>86. Testing Parent Checkbox</h2>
<pre><code>WebElement parent = driver.findElement(By.id("parent"));
parent.click();
List<WebElement> children = driver.findElements(
By.cssSelector(".child-checkbox")
);
for (WebElement child : children) {
System.out.println(child.isSelected());
}</code></pre>
<hr>
<h2>87. Checkbox Inside an Iframe</h2>
<p>If a checkbox is inside an iframe, Selenium must switch into the iframe before interacting with the checkbox.</p>
<pre><code>WebElement frame = driver.findElement(By.id("paymentFrame"));
driver.switchTo().frame(frame);
WebElement checkbox = driver.findElement(By.id("terms"));
checkbox.click();
driver.switchTo().defaultContent();</code></pre>
<hr>
<h2>88. Checkbox Inside Nested Iframes</h2>
<p>For nested iframes, Selenium must switch into each frame in the correct sequence.</p>
<pre><code>driver.switchTo().frame("outerFrame");
driver.switchTo().frame("innerFrame");
driver.findElement(By.id("terms")).click();
driver.switchTo().defaultContent();</code></pre>
<hr>
<h2>89. Checkbox in Shadow DOM</h2>
<p>Some modern web components use Shadow DOM. In such cases, normal Selenium locators may not directly access elements inside a shadow root depending on the page structure and Selenium version.</p>
<pre><code>WebElement host = driver.findElement(By.cssSelector("custom-checkbox"));
SearchContext shadowRoot = host.getShadowRoot();
WebElement checkbox = shadowRoot.findElement(
By.cssSelector("input[type='checkbox']")
);
checkbox.click();</code></pre>
<hr>
<h2>90. Checkbox in a Modal</h2>
<p>When a checkbox is inside a modal, first ensure that the modal is visible and then locate the checkbox within the modal container.</p>
<pre><code>WebElement modal = driver.findElement(By.id("settingsModal"));
WebElement checkbox = modal.findElement(
By.cssSelector("input[type='checkbox']")
);
checkbox.click();</code></pre>
<hr>
<h2>91. Checkbox Inside a Dynamic List</h2>
<pre><code>WebElement item = driver.findElement(
By.xpath("//li[normalize-space()='Java']")
);
WebElement checkbox = item.findElement(
By.cssSelector("input[type='checkbox']")
);
checkbox.click();</code></pre>
<hr>
<h2>92. Checkbox Selection Based on Text</h2>
<pre><code>String option = "Selenium";
WebElement checkbox = driver.findElement(
By.xpath("//div[normalize-space()='" + option + "']/preceding-sibling::input")
);
if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<hr>
<h2>93. Checkbox Automation Flow</h2>
<pre><code>Start
|
v
Open Web Page
|
v
Locate Checkbox
|
v
Is Element Present?
|
+---- No ----> Handle Locator/Error
|
Yes
|
v
Is Checkbox Enabled?
|
+---- No ----> Verify Disabled State
|
Yes
|
v
Check Current State
|
+---- Selected ----> Continue / Deselect if Required
|
+---- Not Selected ----> Click
|
v
Verify Final State
|
v
Continue Test
|
v
End</code></pre>
<hr>
<h2>94. Common Checkbox Test Scenarios</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Scenario</th><th>Expected Result</th></tr>
<tr><td>Checkbox is initially unchecked</td><td>Checkbox should be unselected.</td></tr>
<tr><td>Click unchecked checkbox</td><td>Checkbox should become selected.</td></tr>
<tr><td>Click selected checkbox</td><td>Checkbox should become unselected.</td></tr>
<tr><td>Checkbox is disabled</td><td>User should not be able to interact with it.</td></tr>
<tr><td>Select All is clicked</td><td>Associated checkboxes should be selected.</td></tr>
<tr><td>Select All is deselected</td><td>Associated checkboxes should be deselected.</td></tr>
<tr><td>Mandatory checkbox is not selected</td><td>Appropriate validation should appear.</td></tr>
<tr><td>Checkbox is dynamically loaded</td><td>Automation should wait for the element.</td></tr>
<tr><td>Checkbox is inside iframe</td><td>Automation should switch to the iframe first.</td></tr>
</table>
<hr>
<h2>95. Checkbox Validation Checklist</h2>
<ul>
<li>Verify checkbox is displayed.</li>
<li>Verify checkbox is enabled or disabled as expected.</li>
<li>Verify default selection state.</li>
<li>Verify selection behavior.</li>
<li>Verify deselection behavior.</li>
<li>Verify mandatory checkbox validation.</li>
<li>Verify Select All behavior.</li>
<li>Verify individual selection behavior.</li>
<li>Verify dynamic checkbox behavior.</li>
<li>Verify checkbox behavior across browsers.</li>
</ul>
<hr>
<h2>96. Common Mistakes While Automating Checkboxes</h2>
<ul>
<li>Clicking a checkbox without checking its current state.</li>
<li>Using unstable dynamic IDs.</li>
<li>Using overly broad XPath expressions.</li>
<li>Ignoring visibility and enabled state.</li>
<li>Ignoring synchronization issues.</li>
<li>Using JavaScript click unnecessarily.</li>
<li>Not switching into an iframe.</li>
<li>Not verifying the final checkbox state.</li>
<li>Using indexes when a stable locator is available.</li>
<li>Not handling dynamically refreshed elements.</li>
</ul>
<hr>
<h2>97. Bad Checkbox Automation</h2>
<pre><code>driver.findElement(By.xpath("//input")).click();</code></pre>
<p>This locator may match the wrong input when the page contains many input elements.</p>
<hr>
<h2>98. Better Checkbox Automation</h2>
<pre><code>WebElement checkbox = driver.findElement(
By.cssSelector("input[type='checkbox'][name='terms']")
);
if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<hr>
<h2>99. Best Practices for Checkbox Automation</h2>
<ul>
<li>Prefer stable and unique locators.</li>
<li>Use ID when it is stable and unique.</li>
<li>Use CSS or XPath when necessary.</li>
<li>Always consider the current checkbox state.</li>
<li>Use <code>isSelected()</code> before selecting or deselecting.</li>
<li>Use explicit waits for dynamic applications.</li>
<li>Keep checkbox operations reusable.</li>
<li>Use Page Object Model for larger projects.</li>
<li>Verify expected state after interaction.</li>
<li>Avoid unnecessary JavaScript execution.</li>
<li>Keep test data and locators maintainable.</li>
</ul>
<hr>
<h2>100. Real-World Example: Registration Form</h2>
<pre><code>WebElement terms = driver.findElement(By.id("terms"));
WebElement newsletter = driver.findElement(By.id("newsletter"));
WebElement register = driver.findElement(By.id("register"));
if (!terms.isSelected()) {
terms.click();
}
if (!newsletter.isSelected()) {
newsletter.click();
}
register.click();</code></pre>
<hr>
<h2>101. Real-World Example: Product Filters</h2>
<pre><code>String[] brands = {"Apple", "Samsung", "Dell"};
for (String brand : brands) {
WebElement checkbox = driver.findElement(
By.xpath("//label[normalize-space()='" + brand + "']/preceding-sibling::input")
);
if (!checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>102. Real-World Example: User Permissions</h2>
<pre><code>String[] permissions = {
"Read",
"Write",
"Delete"
};
for (String permission : permissions) {
WebElement checkbox = driver.findElement(
By.xpath("//label[normalize-space()='" + permission + "']/preceding-sibling::input")
);
if (!checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>103. Real-World Example: Notification Settings</h2>
<pre><code>WebElement email = driver.findElement(By.id("emailNotification"));
WebElement sms = driver.findElement(By.id("smsNotification"));
WebElement push = driver.findElement(By.id("pushNotification"));
if (!email.isSelected()) {
email.click();
}
if (!sms.isSelected()) {
sms.click();
}
if (!push.isSelected()) {
push.click();
}</code></pre>
<hr>
<h2>104. Checkbox Automation With Assertions</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}
Assert.assertTrue(
checkbox.isSelected(),
"Terms checkbox should be selected"
);</code></pre>
<hr>
<h2>105. Checkbox Automation With Logging</h2>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
System.out.println("Before click: " + checkbox.isSelected());
if (!checkbox.isSelected()) {
checkbox.click();
}
System.out.println("After click: " + checkbox.isSelected());</code></pre>
<hr>
<h2>106. Checkbox Test Data Example</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Checkbox</th><th>Expected State</th><th>Action</th></tr>
<tr><td>Terms</td><td>Selected</td><td>Select if unchecked</td></tr>
<tr><td>Newsletter</td><td>Optional</td><td>Select based on test data</td></tr>
<tr><td>SMS Alerts</td><td>Unchecked</td><td>Leave unchecked</td></tr>
<tr><td>Admin Access</td><td>Selected</td><td>Verify selection</td></tr>
</table>
<hr>
<h2>107. Checkbox Test Case Format</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Test Case ID</th><th>Test Scenario</th><th>Expected Result</th></tr>
<tr><td>CHK001</td><td>Verify checkbox visibility</td><td>Checkbox should be visible.</td></tr>
<tr><td>CHK002</td><td>Verify checkbox enabled state</td><td>Checkbox should be enabled.</td></tr>
<tr><td>CHK003</td><td>Select checkbox</td><td>Checkbox should become selected.</td></tr>
<tr><td>CHK004</td><td>Deselect checkbox</td><td>Checkbox should become unselected.</td></tr>
<tr><td>CHK005</td><td>Verify default state</td><td>Expected default state should match requirements.</td></tr>
<tr><td>CHK006</td><td>Verify mandatory validation</td><td>Validation should appear when required.</td></tr>
<tr><td>CHK007</td><td>Verify Select All</td><td>All related checkboxes should be selected.</td></tr>
</table>
<hr>
<h2>108. Interview Question: How Do You Handle a Checkbox in Selenium?</h2>
<p>Locate the checkbox using a suitable locator and use the <code>click()</code> method to select or deselect it. The <code>isSelected()</code> method can be used to verify its current state.</p>
<pre><code>WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<hr>
<h2>109. Interview Question: How Do You Check Whether a Checkbox Is Selected?</h2>
<p>Use the <code>isSelected()</code> method.</p>
<pre><code>boolean selected = checkbox.isSelected();</code></pre>
<hr>
<h2>110. Interview Question: How Do You Select Multiple Checkboxes?</h2>
<p>Use <code>findElements()</code> to obtain a list of matching checkboxes and iterate through them.</p>
<pre><code>List<WebElement> checkboxes = driver.findElements(
By.cssSelector("input[type='checkbox']")
);
for (WebElement checkbox : checkboxes) {
if (!checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<hr>
<h2>111. Interview Question: How Do You Select a Checkbox Only If It Is Unchecked?</h2>
<pre><code>if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<hr>
<h2>112. Interview Question: How Do You Deselect a Checkbox?</h2>
<p>If the checkbox is selected, click it to toggle it to the unselected state.</p>
<pre><code>if (checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<hr>
<h2>113. Interview Question: What Is the Difference Between Radio Button and Checkbox?</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Checkbox</th><th>Radio Button</th></tr>
<tr><td>Multiple options can normally be selected.</td><td>Normally one option is selected from a group.</td></tr>
<tr><td>Used for independent selections.</td><td>Used for mutually exclusive choices.</td></tr>
<tr><td>Can be selected and deselected.</td><td>Usually selecting another option changes the selection.</td></tr>
</table>
<hr>
<h2>114. Interview Question: Which Selenium Method Checks Checkbox Selection?</h2>
<p>The <code>isSelected()</code> method checks whether a checkbox or other selectable element is currently selected.</p>
<hr>
<h2>115. Interview Question: What If the Checkbox Is Not Clickable?</h2>
<p>First verify the locator, visibility, enabled state, page synchronization, overlays, iframe context, and custom UI structure. An explicit wait can be used when the checkbox becomes available dynamically.</p>
<hr>
<h2>116. Interview Question: How Do You Handle a Hidden Checkbox?</h2>
<p>First understand how the application's UI is implemented. If the native checkbox is hidden and a visible label or custom control is used, interact with the appropriate visible element rather than blindly forcing a click on the hidden input.</p>
<hr>
<h2>117. Practical Checkbox Automation Project</h2>
<p>Create an automation test for a registration page containing:</p>
<ul>
<li>Terms and Conditions checkbox</li>
<li>Newsletter checkbox</li>
<li>SMS notification checkbox</li>
<li>Product update checkbox</li>
<li>Register button</li>
</ul>
<p>Automation requirements:</p>
<ol>
<li>Open the registration page.</li>
<li>Verify the default checkbox states.</li>
<li>Select Terms and Conditions.</li>
<li>Select Newsletter.</li>
<li>Keep SMS notification unchecked.</li>
<li>Verify the final states.</li>
<li>Click Register.</li>
<li>Validate the resulting page.</li>
</ol>
<hr>
<h2>118. Advanced Checkbox Automation Project</h2>
<p>Create a product filtering automation framework containing multiple brand and category checkboxes.</p>
<ul>
<li>Locate filters using stable locators.</li>
<li>Select multiple brands.</li>
<li>Verify selected states.</li>
<li>Apply filters.</li>
<li>Verify filtered products.</li>
<li>Clear filters.</li>
<li>Verify all filters are reset.</li>
<li>Execute the test across supported browsers.</li>
<li>Integrate the test into TestNG.</li>
<li>Generate execution reports.</li>
</ul>
<hr>
<h2>119. Checkbox Automation Best-Practice Summary</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Practice</th><th>Recommendation</th></tr>
<tr><td>Locator</td><td>Use stable and unique locators.</td></tr>
<tr><td>Selection</td><td>Use <code>isSelected()</code> before toggling state.</td></tr>
<tr><td>Synchronization</td><td>Use appropriate waits for dynamic elements.</td></tr>
<tr><td>Validation</td><td>Verify the final checkbox state.</td></tr>
<tr><td>Multiple Checkboxes</td><td>Use <code>findElements()</code> and loops.</td></tr>
<tr><td>Disabled Checkbox</td><td>Verify <code>isEnabled()</code> before interaction.</td></tr>
<tr><td>Custom Checkbox</td><td>Understand the HTML and interact with the correct visible control.</td></tr>
<tr><td>Iframe</td><td>Switch into the iframe before locating the checkbox.</td></tr>
<tr><td>Framework</td><td>Use reusable methods and Page Object Model.</td></tr>
<tr><td>Assertions</td><td>Validate expected states with assertions.</td></tr>
</table>
<hr>
<h2>120. Conclusion</h2>
<p>Checkbox handling is an essential Selenium WebDriver skill because checkboxes are frequently used in registration forms, settings, filters, permissions, checkout pages, surveys, and other web application workflows. Selenium provides simple methods such as <code>click()</code>, <code>isSelected()</code>, <code>isDisplayed()</code>, and <code>isEnabled()</code> to automate checkbox interactions and validations.</p>
<p>A reliable checkbox automation strategy should use stable locators, check the current selection state before clicking, handle dynamic elements with appropriate synchronization, validate the final state, and account for special cases such as disabled controls, custom checkboxes, iframes, tables, dynamic lists, and Select All functionality.</p>
<p>For structured Selenium learning and practical automation training, visit <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a>. To explore the course demo registration option, visit <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a>.</p>
</div>