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;
}
}
For checkbox with an id
you can simply do
you will get
true
orfalse
as return value for above syntax. You can use it in if clause as normal boolean expression.As per the jQuery documentation there are following ways to check if a checkbox is checked or not. Lets consider a checkbox for example (Check Working jsfiddle with all examples)
Example 1 - With checked
Example 2 - With jQuery is, NOTE - :checked
Example 3 - With jQuery prop
Check Working jsfiddle
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.
You can use this code,
Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!
Here are the syntaxes :
I personally prefer
.prop()
. Unlike.is()
, It can also be used to set the value.You can use any of the following recommended codes by jquery.