How to change the value of a check box onClick using JQuery?
I don't really understand why you would want to do this (the checkbox's value won't be submitted anyways when it's unchecked).
The checked
property on the DOM element will always tell you whether it is checked or not. So you can either get this.checked
(Javascript DOM) or $(this).prop('checked')
(jQuery wrapper).
If you really need to, you should do this:
onclick="$(this).attr('value', this.checked ? 1 : 0)"
or even
onclick="$(this).val(this.checked ? 1 : 0)"
or even better, don't use inline event handlers (like onclick
), but use jQuery's event handling wrappers (.on('click')
or .click()
in older versions).
jsFiddle Demo with jQuery event handling
The problem with your approach
You are using $(this).checked
to get the state of your checkbox. The jQuery object (the one that's returned by the $
function) does not have a checked
property, so it will be undefined
. In Javascript, undefined
is a falsy value, that's why your checkbox's value is always 0
.