views:

1606

answers:

2

All,

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

I am using the following code, but it always returns the count of checked checkboxes regardless of id.

function isCheckedById(id)
{
        alert(id);
        var checked = $("input[@id="+id+"]:checked").length;
        alert(checked);
        if (checked == 0)
        {
                return false;
        }
        else
        {
                return true;
        }
}

Thanks.

+9  A: 
$('#' + id).is(":checked")

that gets if the checkbox is checked.

for an array of checkboxes with the same name you can get the list of checked ones by

var boxes = $('input[name=thename]:checked');

then to loop through them and see what's checked you can do

$(boxes).each(function(){
    //do stuff here with this
});

to find how many are checked you can do

$(boxes).size();
John Boker
hmm.. How to know how many are checked in that checkbox array?
Vincent
just edited it to find the number checked.
John Boker
works perfect !
Vincent
+6  A: 

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />
    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray :checkbox:checked').length > 0;

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
nickf
This works too.. Thanks for the explanation...
Vincent
Nice bit of jQuery...so simple...
Remnant