I have a checkbox and when it is enabled(checked), I want code to execute. It works but when the box is unchecked, the code still works, I would prefer it not work when the box is unchecked. The following code is within a larger jQuery function that works. I just can't get the code to stop working when I uncheck the box. For reference, the check box allows the user to use arrow keys to adjust a canvas element. I want them to be able to adjust when the box is checekd and not be able to adjust when it is unchecked.
$("#hMove728").click( function(){
if($(this).is(':checked')){
alert("checked");
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
case 38:
context.yB -= 2;
break;
case 39:
x += 2;
break;
case 40:
y += 2;
break;
case 37:
x -= 2;
break;
default:
break;
}
update();
})
}
});
Here, check the state of the checkbox inside the event handler:
var moveCheckbox = $("#hMove728");
$( document ).keydown( function( key ) {
if ( moveCheckbox.is(":checked") ) {
// ...
}
});
$(function () {
$('input').on('change', function () {
if ($(this).prop('checked')) {
// It is checked
}
});
});
You have to "unregister" the "keydown" event on your document when you remove the check, or you can make the check inside your keydown function. Like this:
$(document).keydown(function(key) {
if(!$("#hMove728").is(':checked')) return;
switch(parseInt(key.which,10)) {
case 38:
context.yB -= 2;
break;
case 39:
x += 2;
break;
case 40:
y += 2;
break;
case 37:
x -= 2;
break;
default:
break;
}
update();
});
in else put the: $(document).unbind('keydown');
that will unbind the event with the name of keydown on document element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.