admin管理员组

文章数量:1333710

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 /.

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/VnRBL/.

Share Improve this question edited Jul 9, 2014 at 14:27 Sergei Basharov asked Jul 9, 2014 at 14:07 Sergei BasharovSergei Basharov 54k78 gold badges207 silver badges352 bronze badges 3
  • 2 Try using tabindex – Nikhil Talreja Commented Jul 9, 2014 at 14:09
  • see this: stackoverflow./questions/51782054/… – user9402741 Commented Aug 10, 2018 at 8:36
  • Possible duplicate of Disable tabbing between links but inputs – user9402741 Commented Aug 10, 2018 at 8:36
Add a ment  | 

3 Answers 3

Reset to default 4

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/VnRBL/1/

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

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

<element tabindex="number">

Very straightforward to implement.

本文标签: javascriptMake TAB key cycle between inputs of one formStack Overflow