A: 

Can you not just use the tabindex attribute in the html?

If your page is dynamic it might be easier to set this attribute using JS rather than capturing the keypress etc.

matpol
But I will `unbind` this `keydown` event at a later stage. So I think using `tabIndex` will affect the controls outside the container.
rahul
not if you set them as you need them with Jquery
matpol
+2  A: 

Try Keypress instead of Keydown

Also return false so that the keypress normal handling is cancelled.

What appears to be happening is that you are moving the focus then the tab happens, moving it to the select. You need to setfocus, then return false so that the regular tab is cancelled.

$(function(){
$(":input:last","#div1").bind("keydown", function(e){
     if ( e.keyCode === 9 )
     {
         var firstElem = $(":input:first","#div1");
         firstElem.focus();
         return false;
     }
});

});

Russell Steen
No, its not working.
rahul
Thanks @Russel, `return false` did the trick
rahul
+2  A: 

Your example is not working because you are not stopping the keystroke, you set the focus on the first element, and then the tab key is sent, which causes the focus to be changed to the second element.

Try:

$(function(){
  $(":input:last","#div1").bind("keydown", function(e){
    if ( e.keyCode === 9 ) {
      var firstElem = $(":input:first","#div1");
      firstElem.focus();
      e.preventDefault(); // or return false;
    }
  });
});

Check the above example here.

CMS
Thanks @CMS. Its working now.
rahul
You're welcome @rahul.
CMS