.change does not work when element is bound to another?
Not quite sure how to explain this but h开发者_运维技巧ere goes.
I have a function which hides/shows based on a checkbox:
$("#checkbox").change(change_visibility);
function change_visibility() {
if ($("#checkbox").is(":checked")) {
$("#theForm").fadeTo("opacity", "1", function() {
//End Animation
});
} else {
$("#theForm").fadeTo("opacity", "0.3", function() {
//End Animation
});
}
Problem is that now I have bound this checkbox to a button elsewhere and change() is not behaving as I would expect.
$("#myButton").click(function(){
$("#checkbox").attr("checked", true);
});
Even though the checkbox is changing, as it should, it doesnt seem to be calling the change_visibility() function as it does when I click on it manually.
Any idea why this would be?
Whenever you change the status or value of an input element, the change event is not triggered.
But you can trigger it manually:
$("#checkbox").prop("checked", true).change();
The simple way would be to do this
$("#myButton").click(function(){
$("#checkbox").attr("checked", true);
$("#checkbox").change();
});
Sounds like the .change() event doesn't get fired when you change the checkbox manually. But the solution is still very simple. Just call the change_visibility() function yourself:
$("#myButton").click(function(){
$("#checkbox").attr("checked", true);
changeVisibility();
});
Attach an event handler to change
event and call the change method on button click.
$("#checkbox").change(function() {
if (this.checked) {
$("#theForm").fadeTo("opacity", "1", function() {
//End Animation
});
} else {
$("#theForm").fadeTo("opacity", "0.3", function() {
//End Animation
});
});
$("#checkbox").attr("checked", true).change();
Try
$("#myButton").click(function(){
$("#checkbox").attr("checked", true).trigger('change');
});
That should trigger the change event after you dynamically check the box.
精彩评论