- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Way of validating RadioBoxes with jQuery?
Following is how you can validate RadioBoxes with jQuery −
Example
Following is the code −
<!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 −
Advertisements