Disabling jquery when clicking on input fields or textarea

I am trying to fire an event when a certain key is pressed. It works great with this code:

$(document).keypress(function(e){ 
    switch(e.which){ 
            case 96:$("a.quicklinks").trigger('click'); 
            break; 
    } 

But if the user is in the form field, I would like to disable this behavior. How to check if the user enters into the form field for this? Thanks.

+5
source share
3 answers
$(document).keypress(function(e) { 
    if ($(e.target).is('input, textarea')) {
        // event invoked from input or textarea
    }
    ...        
});
+16
source

Perhaps you can set global var

var disable_keyevents = false;
$('textarea,input')
    .focus(function() { disable_keyevents = true })
    .blur(function() { disable_keyevents = true; });

then you just check the disable_keyevents value in the $ (document) .keypress event in front of the switch.

+1
source

, ASCII # 96 - , / " " .

$('#my_form_field').live('keypress', function(e) {
    if (e.keyCode == 96) {
        e.preventDefault();
        // Do stuff.
    }
});
0

All Articles