Reputation: 835
I am working with some complex forms. I have control over the for while tabbing but when there are times to tab back its not working in the order. And I want to make the tabbing work in a circular manner like when tabbed from the last tab-indexed control it should go to the first one and when shift tabbed from the first tab-indexed control it should go to the last one.
My form is completely dynamic. the number of input fields will be determined after the back-end call and there are some input fields before and after and somewhere in the middle of this dynamic fields. So indexing cannot be preset.
Upvotes: 1
Views: 2294
Reputation:
Let your browser deal with it through the tab-index
(if set to the same number for all inputs, it will rely on their order in the HTML) property, and simply send back to the first input when you are on the last one and only tab is pressed, and vice-versa for the first input
const last = document.querySelector('.container input:last-child');
const first = document.querySelector('.container input:first-child');
last.addEventListener('keydown', event => {
if (event.code === 'Tab' && !event.shiftKey) { first.focus(); event.preventDefault(); }
});
first.addEventListener('keydown', event => {
if (event.code === 'Tab' && event.shiftKey) { last.focus(); event.preventDefault(); }
});
input {
display: block;
margin-bottom: -1px;
tab-index: 0;
}
<div class="container">
<input type="text" placeholder="first">
<input type="text" placeholder="second">
<input type="text" placeholder="third">
<input type="text" placeholder="fourth">
</div>
Upvotes: 1