html页面实现回车跳转下一文本框

window.onload = function () {
    //阻止按回车按钮后提交表单的问题
    document.getElementsByTagName("form")[0].onkeydown = function () {
        if (event.keyCode == 13) { return false; }
    };
    var inputs = document.getElementsByTagName("input");
    var index = 1;
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "text" && inputs[i].style.display != "none" && inputs[i].getAttribute("disabled") != "disabled") {
            //给页面上的没有隐藏的文本框设置tabindex顺序值,下文按tabindex顺序跳转
            inputs[i].setAttribute("tabindex", index);
            //监听onkeydown事件,输入回车时实现跳至下一文本框
            inputs[i].onkeydown = goNextInput;
            index++;
        }
    }
};

function goNextInput() {
    if (window.event.keyCode == 13) { //录入回车时才往下一录入框跳
        //下一个录入框的tabindex值
        var nextIndex = parseInt(window.event.srcElement.getAttribute("tabindex")) + 1;
        var inputs = document.getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type == "text" && inputs[i].style.display != "none") {
                var tabIndex = inputs[i].getAttribute("tabindex");
                if (tabIndex != null) {
                    var index = parseInt(tabIndex);
                    if (typeof index == "number" && !isNaN(index) && index == nextIndex) {
                        inputs[i].focus();
                    }
                }
            }
        }
    }
}

 

posted @ 2017-04-06 13:11  chyun2011  阅读(2663)  评论(0编辑  收藏  举报