Checkbox checked property in JQuery

Using JQuery we can check whether a checkbox is checked or not.

Consider you have a check box like below

<input type="checkbox" id="checkbox1"/>

 Using the below JQuery code, you can check whether the above checkbox is checked or not


if ($("#checkbox1").is(':checked')) {
    alert("checked");  // checked
}
else {
    alert("not checked"); // unchecked 
}

Note: is(':checked') returns TRUE if the checkbox is checked else it returns false.

You can also use below code to check checkbox is checked:


if ($("#checkbox1").attr("checked")) {
    alert("Checked");
}
else {
    alert("Unchecked");
}

Note: Since jQuery 1.6, The behavior ofjQuery.attr() has changed. So it is recommended not to use it.

Javascript Code to check checkbox's checked property:


var myCheckbox = document.getElementById('checkbox1');
 
myCheckbox.onchange = function () {
    if (this.checked) {
        alert("checked");
    }
    else {
        alert("not checked");
    }
}

In this way you can check whether a checkbox is checked ot not using JQuery

For more posts on JQuery please visit: JQuery

No comments:

Post a Comment