How can I set tabIndex to keydown or keyup given the active tabIndex element?

$(document).on("keyup", function(e) {
    var code = e.which;
    var currentTabIndex = document.activeElement.tabIndex;
    if (code == 40) {
        alert(currentTabIndex);
        //set tabIndex to currentIndex + 1;
    } else if (code == 39) {
        alert(currentTabIndex);
        //set tabIndex to currentIndex + 1;
    }
    else if (code == 38) {
        alert(currentTabIndex);
        //set tabIndex to currentIndex - 1;
    }
    else if (code == 37) {
        alert(currentTabIndex);
        //set tabIndex to currentIndex - 1;
    }
});

      

see FIDDLE for a demonstration.

+1


source to share


2 answers


You can use .filter()

to select the item with the one you want tabIndex

and then use .focus()

like this:

$('*').filter(function() {
    return this.tabIndex == currentTabIndex + 1;
}).focus();

      

Set focus to any element and then click the down arrow in the following demo:

DEMO



UPDATE

And this is how you could prevent tabs if the target is accepting text input and Left Arrowor is pressed Right Arrow. Below is the complete code :

$(document).on("keyup", function(e) {
    var code = e.which,
        elm = document.activeElement, //capture the current element for later
        currentTabIndex = elm.tabIndex,
        nextTabIndex = code == 40 || code == 39 ? currentTabIndex + 1 :
    code == 38 || code == 37 ? currentTabIndex - 1 : null, //calculate next tab index
        isHoriz = code == 39 || code == 37; //Left or right arrow pressed
    $('[tabindex]').filter(function() {
        if( !$(elm).is(':text,textarea') || !isHoriz ) { //Exclude left/right arrow for text inputs
            return this.tabIndex == nextTabIndex;
        }
    })
    .focus();
});

      

DEMO

+1


source


I would say, just take an element with next or previous tabindex

and call .focus()

on it:

$("[tabindex='" + (currentTabIndex + 1) + "']").focus();

      

or

$("[tabindex='" + (currentTabIndex - 1) + "']").focus();

      

Fiddle Here



EDIT:

So you want to stop the function if ('key pressed' == 'left arrow' or 'right arrow') and 'input type' == 'text'? Then write an if statement doing this exact thing:

if ((code == 39 || code == 37) && $(e.target).attr('type') == "text") return;

      

Place this on the second line of the function.

+1


source







All Articles