Mark
Mark

Reputation: 8291

JQuery can't change focus on keydown

I'm trying to change the focus whenever a user presses tab on the last field. I want to set the focus on to another input field.

I have the following javascript code:

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

And this is my trial html code:

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

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

What am I missing?

Upvotes: 4

Views: 5194

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075845

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

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

Upvotes: 1

nonopolarity
nonopolarity

Reputation: 151264

Yes, those guys get to it before 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/

Upvotes: 1

Harmen
Harmen

Reputation: 22456

You need to stop the event, by returning false. If you do not, the basic browser event is fired after you switched to input1, which means the focus is back at input2.

For example:

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

Upvotes: 7

Related Questions