Way of validating RadioBoxes with jQuery?

Following is how you can validate RadioBoxes with jQuery −


Following is the code −

 Live Demo

<!DOCTYPE html>
<html lang="en">
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <label><input type="radio" name="gen" value="male" />Male</label>
      <label><input type="radio" name="gen" value="female" />Female</label>
      <br />
      <label><input type="radio" name="student" value="yes" />yes<label>
      <label><input type="radio" name="student" value="no" />No</label>
      <br />
      <input type="submit" />
   var nameValues = 'gen;student'.split(';');
   $(function () {
      $("form").on("submit", function (ev) {
         if (nameValues.filter(val => $(`input[name=${val}]:checked`).length === 0).length > 0) {
            console.log("Radio Button is not checked");

To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.

This will produce the following output −

If you don't check the radio button and click the Submit button, you will get an error as shown in the console output below −

To pass the above form validation, you need to check both the radio buttons and click the Submit button.

This will produce the following output −

After clicking the submit button, you will get the following output i.e. no error on console, since we clicked both the radio button above −

Updated on: 09-Nov-2020


Kickstart Your Career

Get certified by completing the course

Get Started