Tab on Form script

This will simulate tabbing and shift+tabbing through a form the way you can normally in a browser.

by Jared Williams

HTML

<section id="page1">
    
    <input type="text" />
    <input type="text" />
    <a href="#">test link</a>
    <input type="text" />
    <select>
        <option>test</option>
    </select>
    <a href="#">test link</a>
    <textarea>hey!</textarea>
    
    <a href="#">test link</a>
    <button>button me?</button>
</section>


<section id="page2">hide me</section>

CSS

#page2 { position: absolute; top: -200px; }

JavaScript

$(function() {
    // gather all inputs of selected types
    var inputs = $('input, textarea, select, button'), inputTo;

    // bind on keydown
    inputs.on('keydown', function(e) {
        
        // if we pressed the tab
        if (e.keyCode == 9 || e.which == 9) {
            // prevent default tab action
            e.preventDefault();

            if (e.shiftKey) {
                // get previous input based on the current input
                inputTo = inputs.get(inputs.index(this) - 1);
            } else {
                // get next input based on the current input
                inputTo = inputs.get(inputs.index(this) + 1);
            }
            
            // move focus to inputTo, otherwise focus first input
            if (inputTo) {
                inputTo.focus();
            } else {
                inputs[0].focus();
            }
        }
    });
});