Way of validating RadioBoxes with jQuery?

jQueryWeb DevelopmentFront End Technology

Following is how you can validate RadioBoxes with jQuery −

Example

Following is the code −

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<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>
<body>
   <form>
      Gender:
      <label><input type="radio" name="gen" value="male" />Male</label>
      <label><input type="radio" name="gen" value="female" />Female</label>
      <br />
      isStudent:
      <label><input type="radio" name="student" value="yes" />yes<label>
      <label><input type="radio" name="student" value="no" />No</label>
      <br />
      <input type="submit" />
   </form>
</body>
<script>
   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");
            ev.preventDefault();
         }
      })
   })
</script>
</html>

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 −

raja
Published on 09-Nov-2020 10:42:23
Advertisements