- HTML5 required checkbox in group?
- 1 Answer
- HTML Form Checkbox with required validation
- Required Validation for a group of checkboxes
- See Also
- HTML: Validating a checkbox with HTML5
- Checkbox validation using JavaScript
- HTML5 required input
- Customised HTML5 messages
- Separating FORM from function
- CSS3 required styles
- References
- Related Articles — Form Validation
- [html] How can I require at least one checkbox be checked before a form can be submitted?
- The answer is
HTML5 required checkbox in group?
I have a form with a group of checkboxes in it ( and some other options but they are irrelevant for this question ). The user sees 7 checkboxes in one form group and i want them to select at least one of them. Is this possible with the «required» attribute in any way? Just like with radiobuttons, i mean. You give one of them in a group the «required» att and you will to choose just one. Or will i have to turn to JQuery or similar? Thanks in advance. Elian Here’s my code to give you an idea:
div class="form-group"> label class="control-label col-md-4" for="optiontext">Specify an optionlabel> div class="col-md-6"> input type="checkbox" name="option[]" value="option1"/> Option 1br> input type="checkbox" name="option[]" value="option2" /> Option 2br> input type="checkbox" name="option[]" value="option3" /> Option 3br> input type="checkbox" name="option[]" value="option4" /> Option 4br> input type="checkbox" name="option[]" value="option5" /> Option 5br> input type="checkbox" name="option[]" value="option6" /> Optione 6br> input type="checkbox" name="option[]" value="option7" /> Option 7 div> div>
Matthias J.
Matthias J.
elk6
elk6
Thanks Matthias, It was no problem using Jquery but i wondered if there was a simpeler version. Since HTML5 makes the rest so simple. 🙂 I’ll post my code that got it working below.
1 Answer
elk6
elk6
Since there is no clear way to do this, i used JQuery for it. Here’s what i did, in case anyone wants to use it. First, i changed all the checkboxes to required and added the «options» class to the form group div ( i wanted to select this specific group ).
div class="form-group options"> label class="control-label col-md-4" for="optiontext">Specify an optionlabel> div class="col-md-6"> input type="checkbox" name="option[]" value="option1" required/> Option 1br> input type="checkbox" name="option[]" value="option2" required/> Option 2br> input type="checkbox" name="option[]" value="option3" required/> Option 3br> input type="checkbox" name="option[]" value="option4" required/> Option 4br> input type="checkbox" name="option[]" value="option5" required/> Option 5br> input type="checkbox" name="option[]" value="option6" required/> Option 6br> input type="checkbox" name="option[]" value="option7" required/> Option 7 div> div>
Then, i added this code ( not my own code, by the way 😉 ) that checks if at least one of the checkboxes is checked and removes the required attribute from all other checkboxes if that is the case.
$(function() var requiredCheckboxes = $('.options :checkbox[required]'); requiredCheckboxes.change(function() if(requiredCheckboxes.is(':checked')) requiredCheckboxes.removeAttr('required'); > else requiredCheckboxes.attr('required', 'required'); > >); >);
HTML Form Checkbox with required validation
The code below shows how to create a single checkbox with “required” validation. Make sure you have not selected the checkbox and then press the submit button to see the error message.
Required Validation for a group of checkboxes
Although the HTML5 ‘required’ validation will work fine with Single checkboxes, there is no HTML5 validation for a group of checkboxes. You will have to do the validation using Javascript.
Here is the validation function for more clarity:
function handleData() var form_data = new FormData(document.querySelector("form")); if(!form_data.has("langs[]")) document.getElementById("chk_option_error").style.visibility = "visible"; > else document.getElementById("chk_option_error").style.visibility = "hidden"; > return false; >
The function collects the FormData() from the form element and check for langs variable. If none of the options are selected, the langs options should be empty.
See Also
HTML: Validating a checkbox with HTML5
While HTML5 form validation is typically about missing or invalid text inputs, there are other form element types that also require attention. One of them being the humble checkbox.
Checkbox validation using JavaScript
Suppose you have a form on your website that at the bottom asks people to «accept the Terms and Conditions» or something similar. Basically you don’t want the form to be submitted unless this is checked.
Using vanilla JavaScript we can prevent form submission as follows:
All this does is confirm before submitting the form that the checkbox is checked. If not, an alert is displayed and focus is moved to the checkbox. Not the prettiest solution, but functional in all browsers that have JavaScript enabled.
HTML5 required input
Adding HTML5 validation to the checkbox is actually very simple. All you need to do is include a required attribute:
This tells the browser that the form should not be allowed to submit without the checkbox checked. Some, but not all, browsers will recognise and enforce this:
The advantage of the HTML5 form validation is that it happens before our JavaScript is called, displays instructions and points the user to the relevant element.
Here you can see screen captures from Firefox and Chrome:
Text alert messages are generated entirely by the browser and will even translate automatically into different languages — something that would be almost impossible using just JavaScript.
The advantage for the user is that it’s obvious whick element is causing the problem and there’s no alert window that needs to be clicked away.
If you’re using an unsupporting browsers all the examples will just display the JavaScript alert box after ignoring the HTML5 validation.
Customised HTML5 messages
As you would hope it is possible to customise the messages that are displayed by the browser with your own text, but this can only be done via JavaScript. You need to check the validity state of the element yourself and set (and clear) the message explicitly:
The block of JavaScript below the form is assigning our custom error message to the checkbox when the page loads. We know that the checkbox is unchecked by default so we need to tell the browser what message to display.
The onchange event handler on the checkbox then toggles the error message. When the checkbox is valid (checked) the message is set to blank which tells the browser that it’s ok for the form to be submitted.
When the checkbox is not checked and the Submit button is clicked an alert is displayed similar to the examples above, but using our text instead of the default.
Here you can see the custom message being displayed in Firefox:
Custom messages can be set in a similar manner for text and other elements, but you will need to check the validity object states (validity.valueMissing | validity.patternMismatch | . ) to determine the current message to display. See the link under References for details.
Separating FORM from function
The previous example was starting to become a bit cluttered with two JavaScript script blocks as well as the onsubmit and onchange event handlers inlined in the HTML.
We can separate the JavaScript code from the HTML and have the required event handlers assigned after the page has loaded using an onload event listener.
Here first is the HTML with all JavaScript removed:
example4 » . > .
field_terms » type=»checkbox» required name=»terms»> I accept the Terms and Conditions
And then the JavaScript to reinstate the event handlers:
The forms behaviour should be unchanged:
While it looks much more complicated, this is a better solution because it allows for the HTML and JavaScript to be maintained separately. The only hooks between them are the id values for the form itself and the checkbox input element. Also gone are any globally defined functions or variables.
The JavaScript can now be moved to a separate file, or converted to a code library allowing for it to be reused with other forms.
The required attribute on checkboxes is supported in Internet Explorer 10 and most/all other browsers except for Safari which currently ignores it.
CSS3 required styles
As we’ve see in other articles the valid/invalid state of a form element can be used to provide visual feedback to the user — displaying a green thumbs up or checkmark for example when the input requirements have been satisfied, or displaying a red outline or warning symbol when they have not.
This is also possible with checkbox elements, just a bit trickier because you can’t really place anything on the inside.
Here’s some sample code to get you started:
The CSS depends of course on how you mark up form fields. In this case we’ve included a label element alongside the checkbox which allows us to reference it using the CSS3 adjacent sibling selector. These styles are all being applied to the label element.
Clicking on the checkbox or the label text will now toggle the checkbox state, and the text will change from red to green. Basically, when the checkbox is happy, the label is happy.
There are also clever ways of styling the label to look like a checkbox and hiding the actual checkbox so you can use your own graphic, font icon or CSS creation:
input[type=»checkbox»]:required < display: none; >input[type=»checkbox»]:required:invalid + label::before < content: "\2610"; padding-right: 0.2em; font-size: 1.6em; color: red ; >input[type=»checkbox»]:required:valid + label::before
In this case we’ve used some UNICODE ‘ballot box’ characters for the on/off state. They are prepended to the label, but actually toggling the checkbox in the background. We know the checkbox is changing because that’s what drives the CSS effect:
The HTML for this example is the same as above.
For more examples like this check out our new article Styling a Yes/No Checklist with CSS.
Did you find any of these examples useful or have any questions? Let us know using the Feedback form below.
References
Related Articles — Form Validation
- HTML HTML5 Form Validation Examples
- HTML Validating a checkbox with HTML5
- JavaScript Preventing Double Form Submission
- JavaScript Form Validation
- JavaScript Date and Time
- JavaScript Password Validation using regular expressions and HTML5
- JavaScript A simple modal feedback form with no plugins
- JavaScript Counting words in a text area
- JavaScript Tweaking the HTML5 Color Input
- JavaScript Credit Card numbers
- JavaScript Allowing the user to toggle password INPUT visibility
- PHP Protecting forms using a CAPTCHA
- PHP Basic Form Handling in PHP
- PHP Measuring password strength
- PHP Creating a CAPTCHA with no Cookies
[html] How can I require at least one checkbox be checked before a form can be submitted?
I have a list of multiple check boxes. The user can check all of them, but at least one should be checked to allow form submission. How can I enforce that requirement?
The answer is
Here’s an example using jquery and your html.
Make all the checkboxes required and add a change listener . If any one checkbox is ticked, remove required attribute from all the checkboxes. Below is a sample code.
Google Chrome
Internet Explorer
Mozilla Firefox
Microsoft Edge
Change listener :
This should have what you need, check out the jsfiddle at the bottom:
The issue with the accepted solution above is that is does not allow for the else condition on form submit (if a box has been selected), thereby preventing form submission — at least when I tried it.
I discovered another solution that effects the desired result more completely IMHO, here:
function valthis() < var checkBoxes = document.getElementsByClassName( 'myCheckBox' ); var isChecked = false; for (var i = 0; i < checkBoxes.length; i++) < if ( checkBoxes[i].checked ) < isChecked = true; >; >; if ( isChecked ) < alert( 'At least one checkbox checked!' ); >else < alert( 'Please, check at least one checkbox!' ); >>
You can either do this on a PHP level or on a Javascript level. If you use Javascript, and/or JQuery, you can check and validate if all the checkboxes are checked with a selector.
Jquery also offers several validation libraries. Check out: http://jqueryvalidation.org/
The problem with using Javascript to validate is that it may be bypassed so it is wise to check on the server too.
Example using PHP and assuming you are calling a PO