rahul
rahul

Reputation: 187050

Problem with giving focus to first element inside a container

I am just trying to cycle the focus between elements inside a particular element when the tab key is pressed. What I want to do is not to set focus to any element which is not a descendant of an element when tab is pressed from the last control inside the element. At that time the focus must be set to the first input element inside the container.

I have done a sample and it its not working, and I am unable to figure out the issue.

Sample can be found here

The complete code is

Script

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

CSS

input.red { width: 200px; border: solid 1px red; }
input { width: 200px; }

HTML

<input type="text" class="red" />
<div id="div1">
    <input type="text" id="txt1" />
    <select id="sel1">
        <option>1</option>
    </select>
    <input type="text" id="txt2" />
</div>

Any help would be appreciated.

Thanks

Edit

Thanks everyone. Problem solved. It was the lack of a return false; statement in the keydown event.

Upvotes: 2

Views: 2059

Answers (3)

Russell Steen
Russell Steen

Reputation: 6612

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;
     }
});

});

Upvotes: 3

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827426

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.

Upvotes: 2

matpol
matpol

Reputation: 3074

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.

Upvotes: 0

Related Questions