SoFunction
Updated on 2025-04-07

JavaScript implements press Enter key to switch focus


<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form>
        <div><input type="text" ></div>
        <div><input type="text" ></div>
        <div><input type="text" ></div>
        <div><input type="text" ></div>
        <div><input type="text" ></div>
        <div><input type="submit" ></div>
    </form>
    <script>
        function is_down(e) {
            var isDown;
            e = e || ;
            switch () {
case 13: //Enter key
case 39: //Move the key to the right
case 40: //Move down key
                    isDown = true;
                    break;
case 37: //Move the key to the left
case 38: //Move up key
                    isDown = false;
                    break;
            }
            return isDown;
        }
        function key_up(){
//When calling the function, the function itself generates this and arguments
//Use this and arguments to find the field and triggered events respectively
            var e=arguments[1];
            return is_down(e) === undefined ? true : handle_element(this, is_down(e));
        }
        function handle_element(field, is_down) {
            var elements = ;
            for (var i = 0, len = -1; i < len; i++) {
                if (field == elements[i]) {
                    break;
                }
            }
            i = is_down ? (i + 1) % len : (i - 1) % len;
//(0===i && is_down) --> Press the down key after the last text box is gained focus
//(-1===i && !is_down) --> Press the up key after the first text box is focused
            if((0===i && is_down)||(-1===i && !is_down)){
                return true;
            }
            elements[i].focus();
            var element_arr = ['button', 'submit', 'reset', 'select-one', 'textarea'];
            if (element_arr.join(',').indexOf(elements[i].type) > -1)
                elements[i].select();
            return false;
        }
//Cancel Enter the default submission form event
        = function(e) {
            e = e || ;
            if( == 13) {
                ? () : ( = false);
            }
        };
//Cross-browser recognition addEventListener and attachEvent(IE)
        function addHandler(element, type, handler) {
            if ()
                (type, handler, false);
            else if ()
                ("on" + type, handler);
            else
                element["on" + type] = handler;
        }
        var elements = [0].elements;
        for (var i = 0, len = ; i < len; i++) {
//Add key_up event handler for keyup event
            addHandler(elements[i], "keyup", key_up);
        }
    </script>
</body>
</html>