jQuery: set focus on the next input field

by gabrieleromanato

HTML

<form id="test" action="#" method="post">

    <div>
        <label for="name">Name</label>
        <input type="text" name="name" id="name"/>
</div>

<div>
        <label for="email">Email</label>
        <input type="text" name="email" id="email"/>
</div>

<div>
        <label for="address">Address</label>
        <input type="text" name="address" id="address"/>
</div>

<p><input type="submit" value="Send"/></p>

</form>

CSS

#test {
    width: 60%;
    margin: 2em auto;
}

#test label {
    display: block;
    margin-bottom: 0.4em;
}

#test div input {
    display: block;
    padding: 0.6em;
    width: 22em;
    border: 1px solid #c0c0c0;
    margin-bottom: 0.4em;
}

#test div input:focus {
    outline: 2px solid orange;
}

JavaScript

(function($) {

    $.fn.focusNextInputField = function() {
        return this.each(function() {
            var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
            var index = fields.index(this);
            if (index > -1 && (index + 1) < fields.length) {

                fields.eq(index + 1).focus();
            }
            return false;
        });
    };

})(jQuery);


$('#name', '#test').focusNextInputField();