Using the HTML5 “required” attribute for a group o

2019-01-01 08:27发布

问题:

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?

UPDATE

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.

UPDATE 2

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 obivous.

回答1:

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.



回答2:

Its a simple trick. This is jQuery code that can exploit the html5 validation by changing the required properties if any one is checked. Following is your html code (make sure that you add required for all the elements in the group.)

<input type=\"checkbox\" name=\"option[]\" id=\"option-1\" value=\"option1\" required/> Option 1
<input type=\"checkbox\" name=\"option[]\" id=\"option-2\" value=\"option2\" required/> Option 2
<input type=\"checkbox\" name=\"option[]\" id=\"option-3\" value=\"option3\" required/> Option 3
<input type=\"checkbox\" name=\"option[]\" id=\"option-4\" value=\"option4\" required/> Option 4
<input type=\"checkbox\" name=\"option[]\" id=\"option-5\" value=\"option5\" required/> Option 5

Following is jQuery script, which disables further validation check if any one is selected. Select using name element.

$cbx_group = $(\"input:checkbox[name=\'option[]\']\");
$cbx_group = $(\"input:checkbox[id^=\'option-\']\"); // name is not always helpful ;)

$cbx_group.prop(\'required\', true);
if($cbx_group.is(\":checked\")){
  $cbx_group.prop(\'required\', false);
}

Small gotcha here: Since you are using html5 validation, make sure you execute this before the it gets validated i.e. before form submit.

// but this might not work as expected
$(\'form\').submit(function(){
  // code goes here
});

// So, better USE THIS INSTEAD:
$(\'button[type=\"submit\"]\').on(\'click\', function() {
  // skipping validation part mentioned above
});


回答3:

I guess there\'s no standard HTML5 way to do this, but if you don\'t mind using a jQuery library, I\'ve been able to achieve a \"checkbox group\" validation using webshims\' \"group-required\" validation feature:

The docs for group-required say:

If a checkbox has the class \'group-required\' at least one of the checkboxes with the same name inside the form/document has to be checked.

And here\'s an example of how you would use it:

<input name=\"checkbox-group\" type=\"checkbox\" class=\"group-required\" id=\"checkbox-group-id\" />
<input name=\"checkbox-group\" type=\"checkbox\" />
<input name=\"checkbox-group\" type=\"checkbox\" />
<input name=\"checkbox-group\" type=\"checkbox\" />
<input name=\"checkbox-group\" type=\"checkbox\" />

I mostly use webshims to polyfill HTML5 features, but it also has some great optional extensions like this one.

It even allows you to write your own custom validity rules. For example, I needed to create a checkbox group that wasn\'t based on the input\'s name, so I wrote my own validity rule for that...



回答4:

HTML5 does not directly support requiring only one/at least one checkbox be checked in a checkbox group. Here is my solution using Javascript:

HTML

<input class=\'acb\' type=\'checkbox\' name=\'acheckbox[]\' value=\'1\' onclick=\'deRequire(\"acb\")\' required> One
<input class=\'acb\' type=\'checkbox\' name=\'acheckbox[]\' value=\'2\' onclick=\'deRequire(\"acb\")\' required> Two

JAVASCRIPT

       function deRequireCb(elClass) {
            el=document.getElementsByClassName(elClass);

            var atLeastOneChecked=false;//at least one cb is checked
            for (i=0; i<el.length; i++) {
                if (el[i].checked === true) {
                    atLeastOneChecked=true;
                }
            }

            if (atLeastOneChecked === true) {
                for (i=0; i<el.length; i++) {
                    el[i].required = false;
                }
            } else {
                for (i=0; i<el.length; i++) {
                    el[i].required = true;
                }
            }
        }

The javascript will ensure at least one checkbox is checked, then de-require the entire checkbox group. If the one checkbox that is checked becomes un-checked, then it will require all checkboxes, again!



回答5:

I had the same problem and I my solution was this:

HTML:

<form id=\"processForm.php\" action=\"post\">
  <div class=\"input check_boxes required wish_payment_type\">
    <div class=\"wish_payment_type\">
    <span class=\"checkbox payment-radio\">
      <label for=\"wish_payment_type_1\">
        <input class=\"check_boxes required\" id=\"wish_payment_type_1\" name=\"wish[payment_type][]\" type=\"checkbox\" value=\"1\">Foo
      </label>
    </span>
    <span class=\"checkbox payment-radio\">
      <label for=\"wish_payment_type_2\">
        <input class=\"check_boxes required\" id=\"wish_payment_type_2\" name=\"wish[payment_type][]\" type=\"checkbox\" value=\"2\">Bar
      </label>
    </span>
    <span class=\"checkbox payment-radio\">
      <label for=\"wish_payment_type_3\">
        <input class=\"check_boxes required\" id=\"wish_payment_type_3\" name=\"wish[payment_type][]\" type=\"checkbox\" value=\"3\">Buzz
      </label>

      <input id=\'submit\' type=\"submit\" value=\"Submit\">
  </div>
</form>

JS:

var verifyPaymentType = function () {
  var checkboxes = $(\'.wish_payment_type .checkbox\');
  var inputs = checkboxes.find(\'input\');
  var first = inputs.first()[0];

  inputs.on(\'change\', function () {
    this.setCustomValidity(\'\');
  });

  first.setCustomValidity(checkboxes.find(\'input:checked\').length === 0 ? \'Choose one\' : \'\');
}

$(\'#submit\').click(verifyPaymentType);

https://jsfiddle.net/oywLo5z4/



回答6:

Inspired by the answers from @thegauraw and @Brian Woodward, here\'s a bit I pulled together for JQuery users, including a custom validation error message:

$cbx_group = $(\"input:checkbox[name^=\'group\']\");
$cbx_group.on(\"click\", function() {
    if ($cbx_group.is(\":checked\")) {
        // checkboxes become unrequired as long as one is checked
        $cbx_group.prop(\"required\", false).each(function() {
            this.setCustomValidity(\"\");
        });
    } else {
        // require checkboxes and set custom validation error message
        $cbx_group.prop(\"required\", true).each(function() {
            this.setCustomValidity(\"Please select at least one checkbox.\");
        });
    }
});

Note that my form has some checkboxes checked by default.

Maybe some of you JavaScript/JQuery wizards could tighten that up even more?



回答7:

we can do this easily with html5 also, just need to add some jquery code

Demo

HTML

<form>
 <div class=\"form-group options\">
   <input type=\"checkbox\" name=\"type[]\" value=\"A\" required /> A
   <input type=\"checkbox\" name=\"type[]\" value=\"B\" required /> B
   <input type=\"checkbox\" name=\"type[]\" value=\"C\" required /> C
   <input type=\"submit\">
 </div>
</form>

Jquery

$(function(){
    var requiredCheckboxes = $(\'.options :checkbox[required]\');
    requiredCheckboxes.change(function(){
        if(requiredCheckboxes.is(\':checked\')) {
            requiredCheckboxes.removeAttr(\'required\');
        } else {
            requiredCheckboxes.attr(\'required\', \'required\');
        }
    });
});


回答8:

Hi just use a text box additional to group of check box.When clicking on any check box put values in to that text box.Make that that text box required and readonly.



回答9:

Here is another simple trick using Jquery!!

HTML

<form id=\"hobbieform\">
        <div>
            <input type=\"checkbox\" name=\"hobbies[]\">Coding
            <input type=\"checkbox\" name=\"hobbies[]\">Gaming
            <input type=\"checkbox\" name=\"hobbies[]\">Driving
        </div>
</form>


JQuery

$(\'#hobbieform\').on(\"submit\", function (e) {
    var arr = $(this).serialize().toString();
    if(arr.indexOf(\"hobbies\") < 0){
        e.preventDefault();
        alert(\"You must select at least one hobbie\");
    }
});

That\'s all.. this works because if none of the checkbox is selected, nothing as regards the checkbox group(including its name) is posted to the server