Toggle click issue with checkbox
Please find the cod开发者_如何学JAVAe below
$("#chkCopy").toggle(function () {
copyDetails();
},
function () {
emptyCopyDetails();
});
// functions which do not have any effect on the checkbox
function copyDetails() {
}
function emptyCopyDetails() {
}
The issue is that checkbox is not showing the checked state.
Demo
Thanks in advance
The .toggle()
interrupts the check, since .toggle()
actually calls e.preventDefault()
on the click
event underneath. Instead of that approach, I'd recommend something like this instead:
$("#chkCopy").change(function () {
if(this.checked) {
copyDetails();
} else {
emptyCopyDetails();
}
});
Here's an updated/working version of your demo with the above approach.
$("#chkCopy").change(function () { alert("1");
},
function () {
alert("2");
});
use change instead of toggle
From the documentation:
Since
.toggle()
internally uses a click handler to do its work, we must unbindclick
to remove a behavior attached with.toggle()
, so otherclick
handlers can be caught in the crossfire. The implementation also calls.preventDefault()
on the event, so links will not be followed and buttons will not be clicked if.toggle()
has been called on the element.
So you can't use toggle()
if you want the check box to be checked and unchecked. You can use click()
instead:
$("#chkCopy").click(function() {
if (this.checked) {
copyDetails();
} else {
emptyCopyDetails();
}
});
take a look at this answer you would accomplish the same thing
Jquery toggle event is messing with checkbox value
精彩评论