In this tutorial you will learn how to check a radio button is checked In JavaScript using change and click event listener with code example.
Dummy HTML Radio Button For Testing
The following HTML code contains three radio buttons labeled “Option 1”, “Option 2”, and “Option 3”, arranged in a group so only one can be selected. There’s also a button labeled “Check Option 2”. This button is intended to programmatically select the second radio button when clicked, as specified by the JavaScript code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checking a Radio Button in JavaScript</title>
</head>
<body>
<h2>Radio Buttons</h2>
<input type="radio" id="radioButton1" name="radioGroup" value="option1"> <label for="radioButton1">Option 1</label><br>
<input type="radio" id="radioButton2" name="radioGroup" value="option2"> <label for="radioButton2">Option 2</label><br>
<input type="radio" id="radioButton3" name="radioGroup" value="option3"> <label for="radioButton3">Option 3</label><br><br>
<button id="checkRadioButton">Check Option 2</button>
</body>
</html>
JavaScript Code to Check if Radio Button is Checked
In the following JS code, “change” event listener listen the changes of a radio button. You can use also use the “click” event listener to detect radio button changes. Then use the checked
property of a radio button to know its state, If it is true
, means radio button is checked.
// Get references to the radio button elements by their IDs
const radioButton1 = document.getElementById("radioButton1");
const radioButton2 = document.getElementById("radioButton2");
const radioButton3 = document.getElementById("radioButton3");
const checkRadioButtonButton = document.getElementById("checkRadioButton");
// Add a click event listener to the button
checkRadioButtonButton.addEventListener("click", () => {
// Check the radio button
radioButton2.click();
});
// Add a click event listener to each radio button
radioButton1.addEventListener("change", () => {
if (radioButton1.checked) {
alert("Option 1 is selected");
}
});
radioButton2.addEventListener("change", () => {
if (radioButton2.checked) {
alert("Option 2 is selected");
}
});
radioButton3.addEventListener("change", () => {
if (radioButton3.checked) {
alert("Option 3 is selected");
}
});
This code sets up event listeners for three radio buttons and a check button:
- When the check button is clicked, it programmatically clicks the second radio button.
- Each radio button triggers an alert when it is checked, indicating which option is selected (Option 1, Option 2, or Option 3).