Coder Perfect

jQuery can be used to see if a checkbox is checked.

Problem

Using the id of the checkbox array, how can I verify if a checkbox in a checkbox array is checked?

I’m using the following code, however regardless of the id, it always returns the number of selected checkboxes.

function isCheckedById(id) {
    alert(id);
    var checked = $("input[@id=" + id + "]:checked").length;
    alert(checked);

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

Asked by Jake

Solution #1

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

If the checkbox is selected, this occurs.

You may get the list of checked checkboxes for an array of checkboxes with the same name by:

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

Then you may cycle through them to see what’s checked:

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

You may find out how many have been checked by doing the following:

$boxes.length;

Answered by John Boker

Solution #2

In your paper, IDs must be unique, thus don’t do anything like this:

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

Rather, remove the ID and select them by name or a contained element:

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

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

Then there’s 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;

Answered by nickf

Solution #3

$('#checkbox').is(':checked'); 

If the checkbox is checked, the code returns true; otherwise, it returns false.

Answered by Prasanna Rotti

Solution #4

All of the strategies listed below are beneficial:

$('#checkbox').is(":checked")

$('#checkbox').prop('checked')

$('#checkbox')[0].checked

$('#checkbox').get(0).checked

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

Answered by justnajm

Solution #5

To see if the checkbox is ticked, use the following jQuery code:

if($('input[name="checkBoxName"]').is(':checked'))
{
  // checked
}else
{
 // unchecked
}

Alternatively:

if($('input[name="checkBoxName"]:checked'))
{
    // checked
}else{
  // unchecked
}

Answered by Kundan roy

Post is based on https://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery