Search code examples
javascriptjqueryhtmltabindex

Setting tabindex to "last element" and "penultimate element" - possible?


In the accepted answer to this question Multiple submit buttons in an HTML form the comment is raised:

Please don't do this without also changing the tab order, so that hitting the tab button will cycle through the buttons as they appear on screen.

My question is: is there a way to set the tabindex on those two buttons to accomplish this ordering without having to assign a specific tabindex to every other tabable element on the page?

My understanding of tabindex values is that specified positive values proceed elements w/o a specified value, so I am at a loss to figure out a way to do this w/o going through and assigning everything else a value.

If indeed, assigning a specific tabindex to every item is the only way, is there some (hopefully short and hopefully jQuery) magic to assign every appropriate element on the page a tabindex of, say, 1?

EDIT
As it looks like the solution is going to involve applying a specific tabindex to every other tabable object -- it seems like an important part of the solution is going to be: is there a convenient way in jQuery to select every tabable object? All s s s and ???


Solution

  • Using Adding tabindex dynamically and fixing button indecies:

    $(":input:not(:hidden)")
      .each(function (i) {
        $(this).attr('tabindex', i + 1);
      });
    var r = $('input.r').attr('tabindex');
    $('input.r').attr('tabindex', $('input.l').attr('tabindex'));
    $('input.l').attr('tabindex', r);
    

    html:

    <input type="submit" value="Next" class="r" />
    <input type="submit" value="Previous" class="l" />
    

    Plunk

    Update - fixed query to select not only inputs (check link in John's comment below):

    $("a[href],area[href],input:not([disabled]),select:not([disabled]),\
    textarea:not([disabled]),button:not([disabled]),iframe,[tabindex],\
    [contentEditable=true]")