If the checkbox is checked, then I only need to get the value as 1; otherwise, I need to get it as 0. How do I do this using jQuery?
$("#ans").val()
will always give me one right in this case:
<input type="checkbox" id="ans" value="1" />
If the checkbox is checked, then I only need to get the value as 1; otherwise, I need to get it as 0. How do I do this using jQuery?
$("#ans").val()
will always give me one right in this case:
<input type="checkbox" id="ans" value="1" />
Jquery :
var test= $("#ans").is(':checked')
and it return true or false.In your function:
Stefan Brinkmann's answer is excellent, but incomplete for beginners (omits the variable assignment). Just to clarify:
It works like this:
Example:
Alerts 'no'
If this is helpful, please upvote Stefan Brinkmann's answer.
Just use
$(selector).is(':checked')
It returns a boolean value.
I've came through a case recently where I've needed check value of checkbox when user clicked on button. The only proper way to do so is to use
prop()
attribute.this worked in my case maybe someone will need it.
When I've tried
.attr(':checked')
it returnedchecked
but I wanted boolean value and.val()
returned value of attributevalue
.