How To Validate Radio Button In Javascript

In web forms, radio buttons are often used to get input from users when they need to select one option from a list of predefined options.
However, validating these radio buttons in JavaScript can be slightly tricky. In this blog post, we will discuss how to easily validate
radio buttons using JavaScript.

Step 1: Create Your HTML Form

First, let’s create a simple HTML form containing radio buttons that we want to validate. For example, we will create a form
asking users for their favorite fruit.


<form id="fruitForm" onsubmit="return validateRadio()">
  Choose your favorite fruit:<br>
  <input type="radio" name="fruit" value="apple"> Apple<br>
  <input type="radio" name="fruit" value="orange"> Orange<br>
  <input type="radio" name="fruit" value="banana"> Banana<br>
  <input type="submit" value="Submit">
</form>

Step 2: Write the JavaScript Function to Validate Radio Buttons

Now that we have our HTML form, let’s write the JavaScript function that will be responsible for validating the radio buttons.
To do this, we will use the querySelectorAll() function to get all the radio buttons with the same name attribute
and loop through them to check if any of them have been selected. If none of them are selected, we will display an alert message
and prevent the form from being submitted.

<><![CDATA[
function validateRadio() {
var radios = document.querySelectorAll(‘input[type=”radio”][name=”fruit”]’);
var selected = false;

for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
selected = true;
break;
}
}

if (!selected) {
alert(“Please choose a fruit!”);
return false;
} else {
return true;
}
}
]]>

Step 3: Add the JavaScript Function to Your HTML File

Finally, add the JavaScript function to your HTML file by either placing it inside a <script> tag or linking
to an external JavaScript file.

Here’s the complete example with the JavaScript function included in the HTML file:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Radio Button Validation Example</title>
</head>
<body>
  <form id="fruitForm" onsubmit="return validateRadio()">
    Choose your favorite fruit:<br>
    <input type="radio" name="fruit" value="apple"> Apple<br>
    <input type="radio" name="fruit" value="orange"> Orange<br>
    <input type="radio" name="fruit" value="banana"> Banana<br>
    <input type="submit" value="Submit">
  </form>
  <script>
<!-- Add your JavaScript function here -->
  </script>
</body>
</html>

Now, when users submit the form without selecting a fruit, they will see an alert message, and the form will not be submitted
until a fruit is selected.

Conclusion

Validating radio buttons in JavaScript can be a bit tricky, but by following these steps, you can easily create a form that
requires users to select one of the given options before submitting. This ensures that you get the necessary input from your
users and increases the data quality of your forms.