Currently I have a textarea with an onkeypress event specified in the HTML tag. I am trying to capture this keypress and save it as a function that will be used to override it, as I want to add another condition to when it is run. Here is the code I am trying to implement.
$(document).ready(function(e) {
var defaultKeypress = $('textarea').keypress;
$('textarea').keypress(function(e) {
if (fieldsChanged) {
fieldsChanged = false;
}
else {
defaultKeypress(e);
}
});
});
The issue I am having is with IE 7 & 8. Both fire the original keypress (even if “defaultKeypress(e);” is commented out) and the new keypress are firing. (Original first, then new). Other than removing the onkeypress attribute from the textarea tag (I can’t do this because if how the code is generated), is there a way to disable that original keypress from firing?
Thanks!
Nutzy
jQuery’s
keypressmethod adds the handler you pass to it and does not override anything. This is very much by design. This way you can attach multiple event handlers to the element in question and not have to worry about clobbering any existing handlers.You actually want to clobber the existing handler. You can’t use
unbindfor this. You can just remove the handler yourself anyway though:Notice I call
defaultKeypresswith the correct scope usingapply, as well as usingreturnto pass its result back. This is all to maintain the standard event handler environment the browser would have called it with.References:
removeAttrapplyfunction