Reputation: 53940
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/.
Upvotes: 3
Views: 4750
Reputation: 9245
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
Upvotes: 3
Reputation: 27058
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();
}
});
Upvotes: 4