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!

5
  • 1
    Shouldn't you use radio buttons if you only want the user to select one? Commented Apr 23, 2013 at 5:38
  • @Willem Ellis He needs atleast once checkbox to be checked. Can have multipe also. Commented Apr 23, 2013 at 5:41
  • 1
    @faanahmed Can you share whatever you have in jQuery Commented Apr 23, 2013 at 5:43
  • Just a note, its better to use PHP delimiter <?php ?> than using just <? ?> Commented Apr 23, 2013 at 5:51
  • @Willem Ellis, i need checkboxes, thank you all great helpers! Commented Apr 23, 2013 at 6:16

5 Answers 5

21

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:

Sign up to request clarification or add additional context in comments.

1 Comment

@lan Can't forget your help, you are talented sir!
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.

Comments

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>

Comments

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.

Comments

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.");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.