Problem with giving focus to first element inside a container

Posted by rahul on Stack Overflow See other posts from Stack Overflow or by rahul
Published on 2010-03-25T14:17:06Z Indexed on 2010/03/25 14:23 UTC
Read the original article Hit count: 371

Filed under:
|
|
|

Hi,

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

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery