Last Updated on October 14, 2021 by Roshan Parihar
In this tutorial, learn how to make checkbox field required in a form with HTML and jQuery. The short answer is to use the :checked
checker and find the length of checkboxes.
The checkboxes are a useful part of a form to provide users multiple choices for selection. You can make it required to get the required data from users. If you do not make the checkbox field required in HTML, your users may skip filling the field and submit the form that will not give you the required data.
Always make a checkbox field required with the method given in this post below. So, let’s find out how to make the checkbox field required in a form in HTML using jQuery.
How to Make Checkbox Field Required in Form in HTML
To make a checkbox field, you need to use a little bit of jQuery to find if one of the checkboxes in the checkbox field is checked or not. The jQuery first gets the length of the checked checkbox if available. If the checkbox is not checked, it gives an alert box that will not allow users to submit the form. See the below example to learn the method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<script> $(document).ready(function () { $('button').click(function() { checked = $("input[type=checkbox]:checked").length; if(!checked) { alert("Please select one checkbox to submit."); return false; } }); }); </script> <form> Please Select Your Gender:<br><br> <input type="checkbox" name="gender[]" id="male" placeholder="Male" required/> <label>Male</label><br> <input type="checkbox" name="gender[]" id="female" placeholder="Female" required/> <label>Female</label><br> <input type="checkbox" name="gender[]" id="other" placeholder="Other" required/> <label>Other</label><br><br> <button type="button">Submit</button> </form> |
Output
The above example contains the checkboxes to give users multiple choices for selection. If you click the button without selecting any checkbox, you will get an alert message to select the checkbox. This will not allow users to submit the form without making any selection.
The required
attribute will not help you in making the checkboxes required. You need some jQuery given above to do perform this task. This is a simple method and useful for anyone who is using forms with checkboxes.
You May Also Like to Read