views:

423

answers:

2

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

A: 

Did you look into the unbind method?

I didn't try this out but I imagine it should work like this.

$(document).ready(function(e) {
    var defaultKeypress = $('textarea').keypress;
    $('textarea').unbind("keypress");
    $('textarea').keypress(function(e) {
        if (fieldsChanged) {
            fieldsChanged = false;
        }
        else {
            defaultKeypress(e);
        }

    });
});
jitter
Unfortunately, this didn't work. I think the unbind is only for functions that are bound from the javascript code. I appreciate your quick response though! This issue has been plaguing me for quite some time now...
Nutzy
+2  A: 

jQuery's keypress method 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 unbind for this. You can just remove the handler yourself anyway though:

var $el = $('textarea'),
    defaultKeypress = $el.attr('onkeypress');

$el.removeAttr('onkeypress');

$el.keypress(function(e) {
    if (fieldsChanged) {
        fieldsChanged = false;
    }
    else {
        return defaultKeypress.apply(this, arguments);
    }
});

Notice I call defaultKeypress with the correct scope using apply, as well as using return to pass its result back. This is all to maintain the standard event handler environment the browser would have called it with.

References:

Crescent Fresh
With some slight modification, this worked perfect! Thanks!
Nutzy