JSFiddle - React, Tailwind, and code Playground

by Eric Howe

HTML

<form>
    <input/>
    <input/>
    <input/>
    <div>
        <input/>
        <input/>
        <input/>
        <input/>
    </div>
</form>

<hr>

<button id="a">Start at the end</button>
<button id="b">Start in the middle</button>

CSS

.start-here {
    background: #0f0;
}

JavaScript

var $all = $('form :input');

function do_things() {
    $('.start-here').focus();
    var focused = $(':focus')[0];
    for(var i = 0; i < $all.length - 1; ++i) {
        if($all[i] != focused)
            continue;
        $all[i + 1].focus();
        break;
    }
    // Must have been focused on the last one or none of them.
    if(i == $all.length - 1)
        $all[0].focus();
}

$('#a').click(function() {
    $('.start-here').removeClass('start-here');
    $('form :input:last').addClass('start-here');
    do_things();
});
$('#b').click(function() {
    $('.start-here').removeClass('start-here');
    $('form :input:eq(3)').addClass('start-here');
    do_things();
});