Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check multiple checkboxes checked using jquery?

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!

like image 546
Irfan Ahmed Avatar asked Apr 23 '13 05:04

Irfan Ahmed


People also ask

How can I check if multiple checkboxes are checked in jQuery?

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.

How can I check all checkboxes?

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.


1 Answers

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:

  • jQuery attribute equals selector: http://api.jquery.com/attribute-equals-selector/
  • :checked selector: http://api.jquery.com/checked-selector/
  • jQuery .length property: http://api.jquery.com/length/
like image 140
Ian Avatar answered Oct 12 '22 22:10

Ian