HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Check if checkbox is checked with jQuery

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withjquerycheckcheckedcheckbox

Problem

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;
}
}

Solution

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



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


    

    


And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

Code Snippets

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

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

Context

Stack Overflow Q#2204250, score: 783

Revisions (0)

No revisions yet.