When using the newer browsers that support HTML5 (FireFox 4 for example);
and a form field has the attribute required='required'
;
and the form field is empty/blank;
and the submit button is clicked;
the browsers detects that the "required" field is empty and does not submit the form;
instead browser shows a hint asking the user to type text into the field.
Now, instead of a single text field, I have a group of checkboxes, out of which at least one should be checked/selected by the user.
How can I use the HTML5 required
attribute on this group of checkboxes?
(Since only one of the checkboxes needs to be checked, I can't put the required
attribute on each and every checkbox)
ps. I am using simple_form, if that matters.
UPDATE
Could the HTML 5 multiple
attribute be helpful here? Has anyone use it before for doing something similar to my question?
It appears that this feature is not supported by the HTML5 spec: ISSUE-111: What does input.@required mean for @type = checkbox?
(Issue status: Issue has been marked closed without prejudice.) And here is the explanation.
It's an old question, but wanted to clarify that the original intent of the question was to be able to do the above without using Javascript - i.e. using a HTML5 way of doing it. In retrospect, I should've made the "without Javascript" more obvious.
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
However, using jQuery, you can easily control if a checkbox group has at least one checked element.
Consider the following DOM snippet:
<div class="checkbox-group required">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
</div>
You can use this expression:
$('div.checkbox-group.required :checkbox:checked').length > 0
which returns true
if at least one element is checked.
Based on that, you can implement your validation check.