Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require that all cheboxes are selected

So I have a field with checkboxes that need to be selected before being submitted. The problem is that it is not a constant number of checkboxes because it depends on the number of values fetched from a database that are to be checked against.

Basically, the number of checkboxes range from 1 to 9.

I am sending the values using ajax so i have not listed the 'checkbale items' in a form, rather, they are in a list. Something like this

Unit 1: <input type="checkbox" name="unit[]" value="1"/>
Unit 2: <input type="checkbox" name="unit[]" value="2"/>
Unit 3: <input type="checkbox" name="unit[]" value="3"/>
Unit 4: <input type="checkbox" name="unit[]" value="4"/>

<input type="submit" value="register units"/>

Question is: How do I ensure that every time,all the checkboxes will be checked before submiting.

like image 681
John Kariuki Avatar asked Mar 20 '23 06:03

John Kariuki


2 Answers

like this:

if($('input[type="checkbox"]:checked').length == $('input[type="checkbox"]').length){
  //all checkboxes are checked.
}

You can also use name attribute to target elements using $('input[name="unit[]"]' and $('input[name="unit[]"]:checked')

like image 59
Milind Anantwar Avatar answered Mar 27 '23 23:03

Milind Anantwar


You can also do it in this way-

     <form name="myForm" action="targetpage.asp" onsubmit="return validateForm();" method="post">  
         Unit 1: <input type="checkbox" name="unit" value="1" />  
         Unit 2: <input type="checkbox" name="unit" value="2" />  
         Unit 3: <input type="checkbox" name="unit" value="3" />  
         Unit 4: <input type="checkbox" name="unit" value="4" />  
         <input type="submit" value="submit" id="XISubmit" />  
     </form>  



 <script>  
     function validateForm() {  
         if (validateCheckbox(document.forms["myForm"]["unit"])) {  
             alert('All good!');  
             return false;  
         }  
         else {  
             alert('Please select all checkboxes.');  
             return false;  
         }  
     }  

     function validateCheckbox(chk) {  
         for (i = 0; i < chk.length; ++i) {  
             if (!chk[i].checked) return false;  
         }  
         return true;  
     }  
 </script>  
like image 23
Manish Gupta Avatar answered Mar 28 '23 00:03

Manish Gupta