Working with radio buttons
Coding with JavaScript
🕑 This lesson will take about 10 minutes
In this lesson, you will learn how to work with HTML radio button elements in JavaScript. We will look at how to check if a radio button has been selected or not using the document.querySelector() method to access a radio button element and checking the checked property of a radio button element (which can be either true or false, indicating if the radio button has been selected or not).
In the example below, radio buttons are 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 ‘Save’ button is clicked.
In the switchMode() function, an if statement checks if the ‘Dark mode’ radio button is selected by using the querySelector() method to access the radio button with the ID ‘dark’, and then checking if the checked property is set to true (this property is set to true if the radio button is selected).
The darkMode() or lightMode() function is called to change the theme of the page depending on which radio button was selected by the user.
Next lesson: Working with checkboxes