Checkboxes, Radio Buttons and Toggles
Check, uncheck and verify checkboxes, radio buttons and switches in Selenium, including custom inputs with hidden native controls and ARIA checked state.
Checking a box sounds like the simplest thing a test can do. In practice it produces a steady stream of bugs: tests that click a checkbox that was already checked (and therefore uncheck it), tests that fail with “element not interactable” because the real input is hidden behind a styled span, and tests that assert on isSelected() for a switch that is not an input at all.
The fix is to stop thinking “click the checkbox” and start thinking “make the checkbox be in state X, then verify it”. This lesson covers native inputs, custom-styled controls, labels, toggles, and ARIA-based widgets.
Native Checkboxes: Set State, Don’t Toggle Blindly
click() toggles. If you do not know the current state, you do not know what a click will do. The idempotent pattern reads isSelected() first and only clicks when the state differs.
void setChecked(WebElement checkbox, boolean shouldBeChecked) { if (checkbox.isSelected() != shouldBeChecked) { checkbox.click(); } if (checkbox.isSelected() != shouldBeChecked) { throw new IllegalStateException("Checkbox did not reach state " + shouldBeChecked); }}
WebElement terms = driver.findElement(By.id("accept-terms"));setChecked(terms, true);setChecked(terms, true); // safe: second call does nothingdef set_checked(checkbox, should_be_checked: bool): if checkbox.is_selected() != should_be_checked: checkbox.click() if checkbox.is_selected() != should_be_checked: raise AssertionError(f"Checkbox did not reach state {should_be_checked}")
terms = driver.find_element(By.ID, "accept-terms")set_checked(terms, True)set_checked(terms, True) # safe: second call does nothingasync function setChecked(checkbox, shouldBeChecked) {if ((await checkbox.isSelected()) !== shouldBeChecked) { await checkbox.click();}if ((await checkbox.isSelected()) !== shouldBeChecked) { throw new Error('Checkbox did not reach state ' + shouldBeChecked);}}
const terms = await driver.findElement(By.id('accept-terms'));await setChecked(terms, true);await setChecked(terms, true); // safe: second call does nothingvoid SetChecked(IWebElement checkbox, bool shouldBeChecked){ if (checkbox.Selected != shouldBeChecked) checkbox.Click();
if (checkbox.Selected != shouldBeChecked) throw new InvalidOperationException($"Checkbox did not reach state {shouldBeChecked}");}
var terms = driver.FindElement(By.Id("accept-terms"));SetChecked(terms, true);SetChecked(terms, true); // safe: second call does nothingThe post-click verification matters. Some apps intercept the click (a confirmation dialog, a disabled state that only applies after validation, a React handler that reverts the change). Without the second check, the helper reports success and the failure surfaces three steps later as something confusing.
isSelected() vs the checked attribute
isSelected() reads the current checked state (the DOM property). The checked attribute in the HTML is only the initial state and does not change when the user clicks.
| Read | What it returns | Use it for |
|---|---|---|
isSelected() / is_selected() / Selected | Live checked state | Almost always |
getDomProperty("checked") (Python: get_property) | Live checked state as a string or boolean | Same as above, explicit |
getDomAttribute("checked") | The HTML attribute: initial state only | Checking the server-rendered default |
getAttribute("checked") | Property-first legacy behaviour | Avoid; ambiguous |
If a test reads the checked attribute after clicking and sees no change, that is the reason.
Radio Buttons
Radio buttons share a name, and exactly one in the group can be selected. Clicking a selected radio does nothing, so the idempotent concern is smaller, but finding the right one is the usual problem. Select by value, which is what the form submits and is normally stable:
driver.findElement(By.cssSelector("input[name='shipping'][value='express']")).click();
String selected = driver.findElements(By.cssSelector("input[name='shipping']")).stream() .filter(WebElement::isSelected) .map(e -> e.getDomAttribute("value")) .findFirst() .orElse(null);assertEquals("express", selected);driver.find_element(By.CSS_SELECTOR, "input[name='shipping'][value='express']").click()
selected = next( (r.get_dom_attribute("value") for r in driver.find_elements(By.CSS_SELECTOR, "input[name='shipping']") if r.is_selected()), None,)assert selected == "express"await driver.findElement(By.css("input[name='shipping'][value='express']")).click();
let selected = null;for (const radio of await driver.findElements(By.css("input[name='shipping']"))) {if (await radio.isSelected()) { selected = await radio.getAttribute('value'); break;}}assert.strictEqual(selected, 'express');driver.FindElement(By.CssSelector("input[name='shipping'][value='express']")).Click();
var selected = driver.FindElements(By.CssSelector("input[name='shipping']")) .FirstOrDefault(r => r.Selected) ?.GetDomAttribute("value");Assert.That(selected, Is.EqualTo("express"));CSS can also do the filtering for you: input[name='shipping']:checked matches the currently selected radio (and checked checkboxes). Because :checked is evaluated by the browser against live state, it is a fast way to read a group in one call.
Custom-Styled Inputs: When the Real Input Is Hidden
Design systems rarely show the browser’s native checkbox. The common implementation hides the real <input> and draws a fake one:
<label class="checkbox"> <input type="checkbox" class="visually-hidden" id="newsletter"> <span class="checkbox__box"></span> Subscribe to newsletter</label>The input is hidden with opacity: 0, width: 0, clip, or positioned off-screen. Clicking it directly fails with ElementNotInteractableException or, if it is covered by the styled span, with an element click intercepted error. Selenium is doing the right thing: a real user cannot click an invisible input either.
The right fix: click what the user clicks
Users click the label or the visible box. So should you. Then verify state on the hidden input, because isSelected() works on hidden inputs even though clicking does not.
WebElement input = driver.findElement(By.id("newsletter"));WebElement label = driver.findElement(By.cssSelector("label[for='newsletter']"));// or, for a wrapping label: input.findElement(By.xpath("./ancestor::label"))
if (!input.isSelected()) { label.click();}assertTrue(input.isSelected());input_el = driver.find_element(By.ID, "newsletter")label = driver.find_element(By.CSS_SELECTOR, "label[for='newsletter']")# or, for a wrapping label: input_el.find_element(By.XPATH, "./ancestor::label")
if not input_el.is_selected(): label.click()assert input_el.is_selected()const input = await driver.findElement(By.id('newsletter'));const label = await driver.findElement(By.css("label[for='newsletter']"));// or, for a wrapping label: input.findElement(By.xpath('./ancestor::label'))
if (!(await input.isSelected())) {await label.click();}assert.ok(await input.isSelected());var input = driver.FindElement(By.Id("newsletter"));var label = driver.FindElement(By.CssSelector("label[for='newsletter']"));// or, for a wrapping label: input.FindElement(By.XPath("./ancestor::label"))
if (!input.Selected) label.Click();
Assert.That(input.Selected, Is.True);A label click toggles its associated input natively, so this works with any framework. Watch for one trap: if the label contains a link (“I accept the [terms]”), clicking the centre of the label may hit the link. Click the visible box (.checkbox__box) instead, or use Actions to click an offset near the left edge of the label.
The JavaScript click shortcut and why to avoid it
executeScript("arguments[0].click()", input) toggles a hidden input without complaint. It also skips the visibility check that would catch a real bug, such as a checkbox that is genuinely unreachable for users. Some frameworks also listen to events on the visible wrapper and never see a script-dispatched click on the input. Use it only as a documented last resort; see the trade-offs in the JavaScript click fallback recipe.
Toggles and Switches
Switches come in three common forms, and each needs a different state check.
| Implementation | Markup | Read state with |
|---|---|---|
| Styled checkbox | <input type="checkbox" role="switch"> | isSelected() |
| ARIA button | <button role="switch" aria-checked="true"> | aria-checked attribute |
| Pressed toggle button | <button aria-pressed="true">Bold</button> | aria-pressed attribute |
| Div soup | <div class="toggle toggle--on"> | A class or, better, ask for ARIA |
isSelected() only applies to option, checkbox and radio input elements. Called on a button role="switch", it returns false regardless of state, which makes a test pass when checking “is off” and fail when checking “is on”. Read the ARIA attribute instead.
boolean isOn(WebElement control) { String tag = control.getTagName().toLowerCase(); String type = control.getDomAttribute("type"); if (tag.equals("input") && ("checkbox".equals(type) || "radio".equals(type))) { return control.isSelected(); } String ariaChecked = control.getDomAttribute("aria-checked"); if (ariaChecked != null) { return ariaChecked.equals("true"); // "mixed" counts as not fully on } return "true".equals(control.getDomAttribute("aria-pressed"));}
void setOn(WebElement control, boolean on) { if (isOn(control) != on) { control.click(); } new WebDriverWait(driver, Duration.ofSeconds(5)).until(d -> isOn(control) == on);}def is_on(control) -> bool: tag = control.tag_name.lower() typ = control.get_dom_attribute("type") if tag == "input" and typ in ("checkbox", "radio"): return control.is_selected() aria_checked = control.get_dom_attribute("aria-checked") if aria_checked is not None: return aria_checked == "true" # "mixed" counts as not fully on return control.get_dom_attribute("aria-pressed") == "true"
def set_on(control, on: bool): if is_on(control) != on: control.click() WebDriverWait(driver, 5).until(lambda d: is_on(control) == on)async function isOn(control) {const tag = (await control.getTagName()).toLowerCase();const type = await control.getAttribute('type');if (tag === 'input' && (type === 'checkbox' || type === 'radio')) { return control.isSelected();}const ariaChecked = await control.getAttribute('aria-checked');if (ariaChecked !== null) { return ariaChecked === 'true'; // "mixed" counts as not fully on}return (await control.getAttribute('aria-pressed')) === 'true';}
async function setOn(control, on) {if ((await isOn(control)) !== on) { await control.click();}await driver.wait(async () => (await isOn(control)) === on, 5000);}bool IsOn(IWebElement control){ var tag = control.TagName.ToLowerInvariant(); var type = control.GetDomAttribute("type"); if (tag == "input" && (type == "checkbox" || type == "radio")) return control.Selected;
var ariaChecked = control.GetDomAttribute("aria-checked"); if (ariaChecked != null) return ariaChecked == "true"; // "mixed" counts as not fully on
return control.GetDomAttribute("aria-pressed") == "true";}
void SetOn(IWebElement control, bool on){ if (IsOn(control) != on) control.Click();
new WebDriverWait(driver, TimeSpan.FromSeconds(5)).Until(_ => IsOn(control) == on);}The wait in setOn is deliberate. Many switches save their state to the server and only flip aria-checked after the request succeeds, or flip it optimistically and revert on failure. A short explicit wait for the final state covers both.
Tip: If your app has switches built from plain
divelements with no ARIA state, that is an accessibility bug as well as a testing problem. Screen readers cannot announce the state either. Raising it as an accessibility issue usually gets it fixed faster than raising it as a test-automation request.
Tri-State Checkboxes
“Select all” checkboxes in tables often have three states: checked, unchecked, and indeterminate (some rows selected). Native checkboxes expose this through the indeterminate DOM property, which has no HTML attribute. Read it with getDomProperty("indeterminate"). ARIA versions use aria-checked="mixed".
WebElement selectAll = driver.findElement(By.cssSelector("[data-testid='select-all']"));boolean indeterminate = Boolean.parseBoolean(selectAll.getDomProperty("indeterminate"));select_all = driver.find_element(By.CSS_SELECTOR, "[data-testid='select-all']")indeterminate = select_all.get_property("indeterminate") # returns a boolconst selectAll = await driver.findElement(By.css("[data-testid='select-all']"));const indeterminate = await driver.executeScript('return arguments[0].indeterminate;', selectAll);var selectAll = driver.FindElement(By.CssSelector("[data-testid='select-all']"));var indeterminate = bool.Parse(selectAll.GetDomProperty("indeterminate"));Clicking an indeterminate checkbox usually selects all, but some libraries clear all instead. Test the actual behaviour your product specifies rather than assuming.
Checkbox Groups and Bulk Selection
For “select these three permissions” style forms, drive a group from data and compare the final state against the expected set:
void selectOnly(WebElement group, Set<String> values) { for (WebElement box : group.findElements(By.cssSelector("input[type='checkbox']"))) { setChecked(box, values.contains(box.getDomAttribute("value"))); }}
WebElement perms = driver.findElement(By.cssSelector("[data-testid='permissions']"));selectOnly(perms, Set.of("read", "write", "export"));def select_only(group, values: set[str]): for box in group.find_elements(By.CSS_SELECTOR, "input[type='checkbox']"): set_checked(box, box.get_dom_attribute("value") in values)
perms = driver.find_element(By.CSS_SELECTOR, "[data-testid='permissions']")select_only(perms, {"read", "write", "export"})async function selectOnly(group, values) {for (const box of await group.findElements(By.css("input[type='checkbox']"))) { await setChecked(box, values.has(await box.getAttribute('value')));}}
const perms = await driver.findElement(By.css("[data-testid='permissions']"));await selectOnly(perms, new Set(['read', 'write', 'export']));void SelectOnly(IWebElement group, ISet<string> values){ foreach (var box in group.FindElements(By.CssSelector("input[type='checkbox']"))) SetChecked(box, values.Contains(box.GetDomAttribute("value")));}
var perms = driver.FindElement(By.CssSelector("[data-testid='permissions']"));SelectOnly(perms, new HashSet<string> { "read", "write", "export" });If checking one box re-renders the group (common with React state lifted to a parent), element references collected before the loop may go stale. In that case, iterate over values and re-find each box by value inside the loop.
Disabled and Read-Only States
Before asserting that a user can’t change something, check how it is disabled:
- Native
disabledattribute:isEnabled()returnsfalse, and clicks do nothing (no exception on most browsers). aria-disabled="true":isEnabled()returnstruebecause the element is not natively disabled. Read the attribute.- Visually disabled via CSS only: neither of the above. Assert on the attribute the app actually uses, and treat a CSS-only disabled state as a bug.
A robust “cannot toggle” test clicks the control and verifies the state did not change, in addition to checking the disabled flag.
Common Pitfalls
| Symptom | Cause | Fix |
|---|---|---|
| Test unchecks a box it meant to check | Blind click() on an already checked box | Read state first; use setChecked |
ElementNotInteractableException | Native input hidden behind styled markup | Click the label or visible box |
isSelected() always false on a switch | Element is a button with aria-checked | Read aria-checked |
checked attribute never changes | Attribute is the initial state only | Use isSelected() or getDomProperty |
| State flips back after click | App reverted after a failed save | Wait for the final state; check for errors |
| Label click opens a link | Label contains an anchor | Click the visual box, not the label centre |
Summary
- Set state idempotently: read, click only if needed, verify.
- Use
isSelected()for native inputs and ARIA attributes for custom switches. - Click what a user clicks (label or visible box) when the native input is hidden, and verify on the input.
- Wait for the final state on switches that persist to the server.
- Handle indeterminate and
aria-disabledexplicitly rather than assuming two states.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.