About this lesson
Uncheck a pre-selected checkbox in Selenium Java
Learn Selenium JavaIntermediateCheckboxes & Radio Buttons
How it works
Unchecking uses the same click() as checking, because a click toggles. What changes is the starting point: a box that loads ticked, like firstSelect5 on the Checkboxes page, which has the checked attribute in its HTML.
That attribute is the box's default, not its live state. After you untick the box, isSelected() and getAttribute("checked") follow the live state (false and null), but getDomAttribute("checked") still returns "true", because the HTML was not changed. Always read the live state when you assert.
About the assignment
The pre-selected row starts with its first box ticked. You confirm that starting state, untick the box, and confirm the new state, the same check a test makes when it turns off a default option.
What you will do
- Find the pre-selected checkbox by the id given in the task.
- Print its
isSelected()result after the labelInitially selected:. - Click it once to untick it.
- Print
isSelected()again after the labelAfter deselect:.
Common mistakes
Clicking twice
A second click ticks the box again, so the after line shows the same value as the before line. One click per change.
Asserting on the HTML attribute
getDomAttribute("checked")keeps returning "true" after you untick the box. It describes the page as loaded, not as it is now.Assuming a default never changes
Which boxes load ticked is decided by the application, not the test. Read the state first, as this task does, instead of hard-coding it.
In a real test suite
Pre-ticked boxes are common for newsletter sign-ups and saved preferences, and tests often need to turn them off. A small helper that sets a checkbox to a wanted state, clicking only when isSelected() differs, handles both this lesson and the last one.
Lesson 22 ticked an empty box. Lesson 24 moves to radio buttons, where you cannot untick an option by clicking it again.
Related lessons
- Handle Checkboxes - Click and VerifyTick an empty box and verify it.
- Get Attribute Value with getAttribute()Why
getAttribute()andgetDomAttribute()can disagree. - isSelected() - Check Selection StateCompare a ticked and an unticked box with
isSelected().
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/Checkboxes");
// TODO: Find pre-selected checkbox firstSelect5
// TODO: Print its initial state
// TODO: Click to deselect
// TODO: Print state after deselecting
driver.quit();
}
}