tags:

views:

22

answers:

1

I have two forms on my page, and when focus is set to one of the forms, i want the user to only be able to tab through the current form.

heres what the html looks like:

<html>
<head>
<script type="text/javascript">
  $(document).ready(function(){ 
    $('form').each(function() {                                
      obj = jQuery(this);
      obj.find('input:last').keydown(function(e) {                       
        if (e.keyCode == 9 && !e.shiftKey) {                       
          e.preventDefault();                                
          obj.find('input:first').focus();                   
        }
      })                                      
      obj.find('input:first').keydown(function(e) {                      
        if (e.keyCode == 9 && e.shiftKey) {                        
          e.preventDefault();                                
          obj.find('input:last').focus();                    
        }
      })
    })
  })
</script>
<body>
  <form>
    <input id="1" />
    <input id="2" />
  </form>
  <form>
    <input id="3" />
    <input id="4" />
  <form>
</body>
</html>

When pressing tab, starting on id 1, the tab order looks like this:

1 <tab> 2 <tab> 3 <tab> 4 <tab> 3 <tab> 4 <tab> ...

Pressing shift + tab starting on id 2:

2 <shift> + <tab> 1 <shift> + <tab> 4 <shift> + <tab> 3 <shift> + <tab> 4 <shift> + <tab> 3 ...

What i would like to have happen is, when on id 1:

1 <tab> 2 <tab> 1<tab> 2 <tab> ...

And backwards:

1 <shift> + <tab> 2 <shift> + <tab> 1 ...

Any ideas why the tab order wraps on the last form, but not on the first?

A: 

Here's the solution:

Replace

obj.find('input:first').focus(); 

with

$(this).closest('form').find('input:first').focus();

and replace

obj.find('input:last').focus(); 

with

$(this).closest('form').find('input:last').focus();

The reason it wasn't working is because the value of obj is getting changed on the second time that .each() runs.

Mark Eirich