Working with checkboxes
Coding with JavaScript
🕑 This lesson will take about 10 minutes
In this lesson, you will learn how to work with HTML checkbox elements in JavaScript. We will look at how to find out if a checkbox has been checked or not using the document.querySelector() method to access a checkbox element and checking the checked property of it (which can be either true or false, indicating if the checkbox has been selected or not).
In the example below, a checkbox is used to switch a page’s colour scheme between dark mode and light mode.
How does this work?
An event listener is used to call the switchMode() function when the checkbox’s label (with the ID ‘switchMode’) is clicked.
In the switchMode() function, an if statement checks if the ‘Dark mode’ checkbox is selected by using the querySelector() method to access the checkbox with the ID ‘darkmode’, and then checking if the checked property is set to true (this property is set to true if the checkbox is selected).
The darkMode() or lightMode() function is called to change the theme of the page depending on if the checkbox was selected by the user.
Next lesson: Keyboard events