Allow submit if user checks a selection of checkboxes

54 Views Asked by At

In a form, I have some checkboxes, these:

 <div class="form-group ">
    <label for="inputName" class="col-lg-2 control-label ">Assistants</label>
      <div class="col-lg-4">
         <div class="checkbox">
           <label><input type="checkbox" name="helper2" value="0">name1</label>
           <label><input type="checkbox" name="helper2" value="1">name2</label>
           <label><input type="checkbox" name="helper2" value="2">name3</label>
         </div>
       </div>                     
  </div>

and then my submit button:

<div class="form-group">
    <div class="col-lg-10 col-lg-offset-2">
        <button type="submit" class="btn btn-primary" id="postme">Submit</button>
    </div>
</div>

and I want the user to check at least 1 checkbox, otherwise the submit button doesn't work. I have found many solutions where one checkbox have to checked but i can't customize it here where I have many checkboxes.. Here is a try...

2

There are 2 best solutions below

2
On BEST ANSWER

I dont know what exactly you are expecting,but the following code detects if any 1 one of the checkbox are checked,it returns false if none are checked.

$("#button-id").on('click',function(){
    var t=$("input[name='helper2']").is(":checked");
    if(t)
    {
            //CODE IF EVEN 1 CHECKBOX IS CHECKED
    }
    else
    {
            //PREVENT FORM SUBMISSION HERE.
    }


  });

P.S:I am using a button with id of button-id, you can use this code on form submit.

0
On

Starting with the linked-to solution: loop over your checkboxes, and as soon as you find one is checked, you can enable the submit button; if you finish the loop and none have been checked, disable it.

If you can't use a loop, use a sequence of if statements: as soon as you find one is checked, enable the button and you are done. Only once you have seen that none are checked can you disable it.