navig8tr
navig8tr

Reputation: 1844

How can I assign a tabindex value to all elements starting with a specific element?

The following code snippet assigns a tabindex value to all elements on a page starting with the first element on the page. I'd like to do the same thing but rather than beginning with the first element on the page I'd like to begin with a specific element and then loop through the remaining elements.

Edit Additional Requirement: I'd like to chose the first element by its id attribute then loop through the rest.

$(function(){
    var tabindex = 1;
    $('input,select').each(function() {
        if (this.type != "hidden") {
            var $input = $(this);
            $input.attr("tabindex", tabindex);
            tabindex++;
        }
    });
});

Upvotes: 1

Views: 89

Answers (1)

PeterKA
PeterKA

Reputation: 24638

You can use :gt(n) psedo selector. The following will assign a tab index starting with the 10th element:

$(function(){
    var tabindex = 1;
    $(':input:not([type=hidden])').filter('input,select').filter(':gt(8)').each(function() {
         var $input = $(this);
         $input.attr("tabindex", tabindex++);
    });
});

UPDATE

As for the ID requirement, you would have to loop through the elements and elect to change those that meet the requirement:

$(function(){
    var tabindex = 1;
    $(':input:not([type=hidden])').filter('input,select').each(function() {
        if( $(this).is('#desired_id') || tabindex > 1 ) {
            var $input = $(this);
            $input.attr("tabindex", tabindex++);
        }
    });
});

Upvotes: 2

Related Questions