All challenges · Core Interactions

Challenge 10 of 29 · Building fluency · Core Interactions

Interact with Checkboxes

Change the state of two checkboxes in opposite directions. You practise targeting checkboxes by role and the actions made for them.

Skills you will practise

  • the checkbox role
  • check and uncheck
  • state changes

The concept

Clicking a checkbox toggles it, which means the result depends on its starting state. If it was already ticked, your click unticks it. Playwright's check() and uncheck() remove the guesswork: check() ensures the box ends up ticked and uncheck() ensures it ends up unticked, regardless of where it started. Both verify the state changed and throw if it did not.

Checkboxes have the checkbox role and take their accessible name from their label, so getByRole('checkbox', { name: 'Subscribe to newsletter' }) reads like the UI.

Assert the final state with toBeChecked() or not.toBeChecked().

The fragile version

Fragile
await page.locator('input[type=checkbox]').first().click();
await page.locator('input[type=checkbox]').last().click();

Why it breaks: click() toggles, so the outcome depends on the initial state. first() and last() depend on order, which changes when a new option is added.

A robust Playwright version

Robust
await page.getByRole('checkbox', { name: 'Email updates' }).check();
await page.getByRole('checkbox', { name: 'SMS updates' }).uncheck();
await expect(page.getByRole('checkbox', { name: 'Email updates' })).toBeChecked();
await expect(page.getByRole('checkbox', { name: 'SMS updates' })).not.toBeChecked();

Each action states the intended end state, and the assertions confirm it.

This is a general example on a made-up page, not the challenge’s reference solution.

Common mistakes

  • Using click() and assuming the starting state.
  • Reading isChecked() once instead of using a retrying assertion.
  • Locating custom checkboxes by a hidden <input> when the visible control is elsewhere.

FAQ

What is the difference between click() and check()?

click() toggles; check() guarantees the checkbox ends up checked.

How do I assert a checkbox is unticked?

await expect(box).not.toBeChecked().

Do check() and uncheck() work on radio buttons?

check() works on radio buttons. uncheck() does not apply to radios.

Try it

Practise this in Challenge 10. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Challenges 1 to 10 are open without an account; create a free one any time to keep your progress. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.