How to get the last (max) tabindex from an html form using jQuery

Asked

Viewed 425 times

2

I need to get the last 'tabindex' of a form for when the user clicks 'tab' or 'enter' back to the first.

Follows current code:

$(':input').keydown( function(event) {

    if ( (event.which === 13 || event.which === 9) && !event.shiftKey ) {
        node = $(this);
        currentIndex = node.attr('tabindex');
        // if ( currentIndex > 0 ) {
        if ( currentIndex > 0 && currentIndex < **MAX_TABINDEX** ) 
            event.preventDefault();
            currentIndex++;
            $('[tabindex=' + currentIndex + ']').focus();
            $('[tabindex=' + currentIndex + ']').select();
        } else {
            $('[tabindex=1]').focus();
            $('[tabindex=1]').select();
        }    
    }

Any idea?

  • Or you can check if the last element is with Focus, if yes, by pressing TAB or ENTER sends Focus pro first...

  • @Earendul how do I identify the last element? I mean, dynamically and not just by putting the name of the object, how? Something like 'last(':input');'

  • 1

    Thus: $("input:last"). https://api.jquery.com/last/

2 answers

3


You can check if the last element is with Focus, if yes, by pressing TAB or ENTER sends Focus pro first. Example:

$(':input').keydown( function(event) {
  if ( (event.which === 13 || event.which === 9) && !event.shiftKey ) {
    var idx = $(':input').index(this) + 1; //index atual
    var idx_total = $(':input').length; // index do ultimo
    event.preventDefault();
    if (idx == idx_total) { // se for o ultimo volta pro primeiro
      $('input:eq(0)').focus();
    }
    else {
      $('input:eq('+idx+')').focus(); // senao focus no proximo
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p><input id="entrada1" type="text"></input></p>
<p><input id="entrada2" type="text"></input></p>
<p><input id="entrada3" type="text"></input></p>
<p><input id="entrada4" type="text"></input></p>

  • I only made one change because as my first field with 'tabindex' is hidden, I used { $('[tabindex=1]'). Focus(); } instead of 'input:first'. Thank you!!! =)

1

Here Voce mounts an array of tabs

 var size=$('#ui-tabs >ul >li').size();

Soon the last one will be the size -1;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.