Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling jquery keypress when in input or textarea fields

Tags:

jquery

I'm trying to fire off an event when a certain key is pressed. It works fine with this code:

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

But, if the user is in a form field, I'd like to disable this behavior. How do I test whether the user is typing in a form field to do this? Thanks.

like image 888
Bill Avatar asked Nov 14 '09 19:11

Bill


2 Answers

$(document).keypress(function(e) { 
    if ($(e.target).is('input, textarea')) {
        // event invoked from input or textarea
    }
    ...        
});
like image 122
Darin Dimitrov Avatar answered Sep 18 '22 02:09

Darin Dimitrov


Maybe you can set a global var

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

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

like image 22
Marco Avatar answered Sep 22 '22 02:09

Marco