I want to check if a certain check box is selected using JavaScript/jQuery.
Here is the code I tried:
var a;
if ($("#add_desc").checked == 1){
a = "true";
}else{
a= "false";
}
I have also tried:
var a;
if ($("#add_desc").checked){
a= "true";
}else{
a= "false";
}
It always returns false once I alert the variable a
.
Any idea why it won't work for me? Am I doing it wrong?
Thanks!
To get the value of the checked
property on a checkbox input, use the .prop()
method, or get the value directly from the DOM element. [0]
returns the first selected DOM element.
var a;
if ($("#add_desc")[0].checked){
a= "true";
}else{
a= "false";
}
or
var a;
if ($("#add_desc").prop("checked")){
a= "true";
}else{
a= "false";
}
Edit
For versions of jQuery older than 1.6, .prop
didn't exist, use .attr
as a direct replacement.
简单,
var a = $('#element:checkbox').is(':checked');
The "jQuery way" would be to use .is(":checked")
:
var a;
if ($("#add_desc").is(":checked")){ // box is checked
a = "true";
} else{ // box is not checked
a= "false";
}
I use this a lot in my web apps and it works perfectly.
From the jQuery .is
documentation page :
Unlike other filtering methods, .is() does not create a new jQuery object. Instead, it allows you to test the contents of a jQuery object without modification. This is often useful inside callbacks, such as event handlers.
try:
if ($('#add_desc').is(':checked')) {
a = "true";
} else {
b = "false";
}
you may also not want to use strings, ie use true
and false
instead of "true"
and "false"
Try
$get("#add_desc").checked == true
Also
$("#add_desc").prop("checked", true);
$("#add_desc").prop("checked", false);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.