JQuery cannot change focus on keydown

I try to change focus whenever a user clicks a tab in the last field. I want to focus on a different input field.

I have the following javascript code:

$("#input2").keydown( function() { if(event.which == 9) { $("#input1").focus(); } } ); 

And this is my test html code:

 <div id="inputArea1"> <input id="input1" /> <input id="input2" /> </div> 

It seems to work with keyup (changing part of focus), but again I don't get what I want with keyup.

What am I missing?

+4
source share
3 answers

You need to stop the event by returning false . If you do not, the main browser event will be fired after switching to input1 , which means that focus returns to input2 .

For instance:

 $("#input2").keydown(function(e){ if(e.which == 9){ $("#input1").focus(); return false; } }); 
+7
source

You probably need to cancel the default event handling by the browser, returning false from your keydown handler, like this ( live example ):

 $("#input2").keydown( function(event) { if(event.which == 9) { $("#input1").focus(); return false; } } ); 
+1
source

Yes, these guys get to me.

Another jQuery way is to use event.preventDefault()

 $("#input2").keydown( function() { if(event.which == 9) { event.preventDefault(); $("#input1").focus(); } } ); 

Live example: http://jsfiddle.net/ebGZc/1/

+1
source

All Articles