Pooja in Web Development

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) {
    var checked = $("input[@id=" + id + "]:checked").length;

    if (checked == 0) {
        return false;
    } else {
        return true;

4 Answers

0 votes

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" />

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;
0 votes
$('#' + 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:

    // Do stuff here with this

To find how many are checked you can do:

0 votes

All following methods are useful:





It is recommended that DOMelement or inline "this.checked" should be avoided instead jQuery on method should be used event listener.

0 votes

jQuery code to check whether the checkbox is checked or not:

  // checked
 // unchecked


    // checked
  // unchecked

Related questions


Follow Us

Stay updated via social channels

Twitter Instagram LinkedIn Instagram