Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  181] [ 3]  / answers: 1 / hits: 16993  / 12 Years ago, fri, april 20, 2012, 12:00:00

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!


More From » jquery

 Answers
40

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.


[#86107] Thursday, April 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckaylab

Total Points: 311
Total Questions: 120
Total Answers: 93

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;