6

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!

Irfan Ahmed
  • 9,136
  • 8
  • 33
  • 54

5 Answers5

20

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:

Ian
  • 50,146
  • 13
  • 101
  • 111
2

If you want at least one checkbox checked, you can use this

var somethingChecked = false;
$("input[type=checkbox]").each(function() {
  if(this).is(':checked')) {
    somethingChecked = true;
  }
});
if(!somethingChecked) {
  alert("You haven't checked anything yet");
}

What this does is initialize a variable to false. Then the script loops through all inputs of type checkbox. If the item is checked, set the variable to true. Finally, check if the variable is still false. If it is, then show an error.

Robbert
  • 6,481
  • 5
  • 35
  • 61
1

This code work well for me,here i convert array to string with ~

    <input type="checkbox" value="created" name="today_check"><strong>Created</strong>
    <input type="checkbox" value="modified" name="today_check><strong>Modified</strong>
 <a class="get_tody_btn">Submit</a>

<script type="text/javascript">
    $('.get_tody_btn').click(function(){
        var vals = "";
        $.each($("input[name='today_check']:checked"), function(){  
            vals += "~"+$(this).val();  
        });
        if (vals){
            vals = vals.substring(1);
        }else{
            alert('Please choose atleast one value.');
        }


    });
</script>
Sandeep Sherpur
  • 2,418
  • 25
  • 27
0

Assuming you have #my_form as the ID of your form, you could do

$("#my_form input[type=checkbox]:checked"). // ... do something

to select and do something with the checked checkboxes. You can also do

$("#my_form input[type=checkbox]").each(function(idx, elem) {
   var is_checked = $(this).prop("checked");
   // Do something with is_checked
});

to iterate through all the checkboxes and check whether they are checked or not.

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
0

First of all id of the checkboxes should be unique.

Do like this

<? 
$checkBoxCount = 0;
foreach($cities as $city) { ?>
    <input type="checkbox" name="city[]" value="<?=$city->id?>" id="chkbox-<?=$checkBoxCount?>" />
<? } ?>

Now in jQuery check like this to get all the checkboxes thats checked.

var checkCount = $("input[name='city[]']:checked").length;

if(checkCount == 0)
{
   alert("Atleast one checkbox should be checked.");
}
kiranvj
  • 32,342
  • 7
  • 71
  • 76