Sergei Basharov
Sergei Basharov

Reputation: 53940

Make TAB key cycle between inputs of one form

I have a a number of <form> elements, like 2-3 forms, on one page. How can I make TAB key switch in cycle between inputs of one form, not go to next form when the last input of one form is reached?

Here is the fiddle with two forms http://jsfiddle.net/VnRBL/.

Upvotes: 3

Views: 4750

Answers (3)

hex494D49
hex494D49

Reputation: 9245

I believe this is what you're looking for

window.onload = function() {
    var i, f = document.getElementsByTagName("FORM");
    for(i = 0; i < f.length; i++){
        (function(i){
        f[i].elements[f[i].length-1].onkeydown = function(e) {  
            var keyCode = e.keyCode || e.which; 
            if(keyCode == 9) { 
                f[i].elements[0].focus();
                e.preventDefault();
            }
        };
        })(i);
    }
};

Check working jsFiddle

Upvotes: 3

Gio Polvara
Gio Polvara

Reputation: 27058

First of all you shouldn't do this because it's not what the user expects.

If you really need to you have to put a key listener on your last form element and check if the user pressed the tab, in that case you give focus to the first element.

Here's an example based on your JsFiddle http://jsfiddle.net/VnRBL/1/

$('#last').on('keydown', function (evt) {
    if(evt.keyCode === 9) { // Tab pressed
        evt.preventDefault();
        $('#first').focus();
    }
});

Upvotes: 4

redditor
redditor

Reputation: 4316

<element tabindex="number">

Very straightforward to implement.

Upvotes: 1

Related Questions