Pete
Pete

Reputation: 7579

jQuery simulate tabbing: use keypress event to check for focus and advance to next

I have a form. The user presses enter. Their keypress is captured, and I'd like my script to advance focus to the next visible form element in the current form.

My current idea is that I need to get the list of inputs to cycle focus through, but I'm stuck on the concept of advancing--like, how do I figure out what the "next" one that it needs to go to is? Here's my code so far.

$('.myitems input').on('keydown', function(e){
  if ( e.which == 13 ) {

    // Get list of items I want to iterate through
    var fields = $('.myitems input:visible');

    // ...Now what...
  }

});

I'd basically like to shift focus to the next visible input in the set of items. I'm guessing that in order to do this I need to scan those items, figure out which one has focus, then assign focus to the next one in the list.

But I can't think of any way to do this in a reasonably performance efficient manner. Any ideas?

Upvotes: 1

Views: 45

Answers (1)

MinusFour
MinusFour

Reputation: 14423

This will cycle focus amongst sibling inputs. I use nextAll just in case there's something else besides the input.

$('input.items').on('keydown', function(e){
  if ( e.which == 13 ) {
   var $next = $(this).nextAll('input');
    if($next.length === 0){
      $next = $(this).siblings('input');
    }
    $next.first().focus();
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input class="items" type="text"> <br>
  <input class="items" type="text"> <br/>
  <input class="items" type="text"> <br/>
  </form>

Upvotes: 1

Related Questions