i am new to the jquery, it is quite interesting, but i am having a little problem, i am populating multiple checkboxes from database using foreach loop like this,
<? foreach($cities as $city) { ?>
<input type="checkbox" name="city[]" value="<?=$city->id?>" id="city[]" />
<? } ?>
i want to restrict user to check atleast one checkbox, i know how to do this with only one checkbox, but got confused with this kind of array in jquery, any help will be greatly appreciated! Many thanks in advance!
Using jQuery is(':checked')change(function(ev) { if ( $(this).is(':checked') ) console. log('checked'); else console. log('not checked'); }); If multiple checkboxes match the jQuery selector, this method can be used to check if at least one is checked.
In order to select all the checkboxes of a page, we need to create a selectAll () function through which we can select all the checkboxes together. In this section, not only we will learn to select all checkboxes, but we will also create another function that will deselect all the checked checkboxes.
To find how many checkboxes are checked, you can use something like:
var checkedNum = $('input[name="city[]"]:checked').length;
if (!checkedNum) {
// User didn't check any checkboxes
}
Since you're providing the same name
attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"]
to target and find them all. But to find out how many specifically are checked, you can add the :checked
selector. An alternative to this is using $('input[name="city[]"]').filter(":checked")
.
Finally, !checkedNum
will only pass if checkedNum
is 0, since 0 is falsey. Any other number is truthy, and wouldn't satisfy the condition !checkedNum
.
References:
:checked
selector: http://api.jquery.com/checked-selector/
.length
property: http://api.jquery.com/length/
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