Make TAB key cycle between inputs of one form

旧时模样 提交于 2019-12-22 09:28:10

问题


I have a a number of <form> elements, like 2-3 forms, on one page. How can I make TAB key switch in cycle between inputs of one form, not go to next form when the last input of one form is reached?

Here is the fiddle with two forms http://jsfiddle.net/VnRBL/.


回答1:


I believe this is what you're looking for

window.onload = function() {
    var i, f = document.getElementsByTagName("FORM");
    for(i = 0; i < f.length; i++){
        (function(i){
        f[i].elements[f[i].length-1].onkeydown = function(e) {  
            var keyCode = e.keyCode || e.which; 
            if(keyCode == 9) { 
                f[i].elements[0].focus();
                e.preventDefault();
            }
        };
        })(i);
    }
};

Check working jsFiddle




回答2:


First of all you shouldn't do this because it's not what the user expects.

If you really need to you have to put a key listener on your last form element and check if the user pressed the tab, in that case you give focus to the first element.

Here's an example based on your JsFiddle http://jsfiddle.net/VnRBL/1/

$('#last').on('keydown', function (evt) {
    if(evt.keyCode === 9) { // Tab pressed
        evt.preventDefault();
        $('#first').focus();
    }
});



回答3:


<element tabindex="number">

Very straightforward to implement.



来源:https://stackoverflow.com/questions/24655922/make-tab-key-cycle-between-inputs-of-one-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!