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 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')
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With