Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a keydown event interfering with form fields?

I've bound some events to happen on left and right arrow key press like so:

$(document).keydown(function(e) {
    switch(e.which) {
        case 39: $("#next").trigger('click');
        break;

        case 37: $("#prev").trigger('click');
        break;              
    }
});

However, obviously if you are in a form and press left and right to move through text, these events fire.

How do I change this so that that doesn't happen?

like image 742
Rich Bradshaw Avatar asked Aug 05 '10 13:08

Rich Bradshaw


People also ask

How do you prevent a number from Keydown?

Use the keypress event instead. It's the only key event which will give you information about the character that was typed, via the which property in most browsers and (confusingly) the keyCode property in IE. Using that, you can conditionally suppress the keypress event based on the character typed.

What is a Keydown event?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What are KeyUp Keydown events?

KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.


2 Answers

You could check the target of the event (more information here)

$(document).keydown(function(e) {
    //var target = (e.target) ? e.target : e.srcElement; // IE uses srcElement
    // jQuery seems to handle this, so e.target should be fine

    if(e.target.nodeName != 'INPUT') {
        switch(e.which) {
            case 39: $("#next").trigger('click');
            break;

            case 37: $("#prev").trigger('click');
            break;              
        }
    }
});

or you could prevent the event from bubbling up by attaching an event handler to the input elements:

$('input').keydown(function(e) {
    e.stopPropagation();
});

Update:

Likewise you might want to test the node name for TEXTAREA.

Here is an example: http://jsfiddle.net/86CKw/1/

like image 114
Felix Kling Avatar answered Oct 04 '22 19:10

Felix Kling


This is the most elegant solution I could find:

$(document).ready(function() {
  $(document).keypress(function() {
    if ( this !== event.target && (/textarea|select/i.test( event.target.nodeName ) || event.target.type === "text") ) {
      return;
    }

    // deal with the events here
    ...

  }); 
});
like image 43
Paul Ardeleanu Avatar answered Oct 04 '22 19:10

Paul Ardeleanu