How to stop keydown event interfering with form fields?

I bound some events to the left and right arrow keys, as shown below:

$(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 around the text, these events fire.

How can I change this so that this does not happen?

+4
source share
3 answers

You can check the purpose 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 can prevent this event from being activated by adding an event handler to the input elements:

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

Update:

Similarly, you can test the node name for TEXTAREA .

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

+11
source

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 ... }); }); 
+2
source
 if (e.target.closest('form').length===0) { // keypress did not occur inside a form. handle it. } 
0
source

All Articles