Select and Focus next input on enter


#1

How do I do so that when the user clicks enter, it selects and focus the next input ?


#2

Have found a solution? I’m searching for this at the moment and have no idea yet.


#3

one solution would be to put your input fields in a form, the enter key will launch the submit function, so in this function you can manage your business.


#4

This is javascript and might need some tweaking but will give you something to base on.

PS: This wasn’t me, I just use it in one of my systems. It’s somewhere in Stackoverflow.

function EnterNextInput() {
    $("body").on("keydown", "input, select", function (e) {
        var self = $(this)
          , form = self.parents("form:eq(0)")
          , focusable
          , next
          , prev
        ;

        if (e.shiftKey) {
            if (e.which === 13) {
                focusable = form.find("input,select").filter(":visible");
                prev = focusable.eq(focusable.index(this) - 1);

                if (prev.length) {
                    prev.focus();
                }
            }
        }
        else
            if (e.which === 13) {
                focusable = form.find("input,select").filter(":visible");
                next = focusable.eq(focusable.index(this) + 1);
                if (next.length) {
                    next.focus();
                } else {
                    form.submit();
                }
                return false;
            }
        return false;
    });
}