6

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.

3 Answers 3

16
$(document).keypress(function(e) { 
    if ($(e.target).is('input, textarea')) {
        // event invoked from input or textarea
    }
    ...        
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

This code will trigger when the user presses ASCII character #96 inside your form - you may use this to disable / modify the "default code" for this keypress.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.