0

I have multiple checkbox on my form. I need to make user to select atleast one checkbox or else the form will not submit. I tried required attribute but it checks if user has checked all check boxes.

How to do this?

  • See http://stackoverflow.com/questions/6218494/using-the-html5-required-attribute-for-a-group-of-checkboxes – Matthew Sant Dec 13 '14 at 09:58
  • give them the same `class` and write a `for` loop to iterate over them and `if` at least one is checked raise a flag to `true` – nicholaswmin Dec 13 '14 at 10:10

2 Answers2

2

One solution is to add required attributes to all the checkboxes, and when at least one of these checkboxes is checked, remove the required attributes for all the checkboxes using jQuery.

var requiredCheckboxes = $(':checkbox[required]');

requiredCheckboxes.change(function(){
    if(requiredCheckboxes.is(':checked')) {
        requiredCheckboxes.removeAttr('required');
    }
    else {
        requiredCheckboxes.attr('required', 'required');
    }
});

DEMO

user2466202
  • 1,205
  • 10
  • 8
0

You can use Javascript that just loops through your html checkboxes and sets the Variable issomethingchecked to TRUE if at least one of them is cheched .

demo http://jsfiddle.net/updpxrfj/2/

        var checkboxElements = document.getElementsByTagName("input");
        var issomethingchecked = false;

        for(var i = 0; i < checkboxElements.length; i++) {

        if(checkboxElements[i].type.toLowerCase() == 'checkbox') {

            if (checkboxElements[i].checked == true) {
                issomethingchecked = true;
            }

        }

            if (issomethingchecked === true) {
                // Continue with submiting the form
                  console.log(issomethingchecked);
            }
}
Alexander
  • 171
  • 2
  • 10