1

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.

JsNgian
  • 795
  • 5
  • 19
  • Possible duplicate of [How to repeat the tabindex from 1 after it has gone to the last element with a tabindex?](https://stackoverflow.com/questions/14314659/how-to-repeat-the-tabindex-from-1-after-it-has-gone-to-the-last-element-with-a-t) – VLAZ Dec 19 '18 at 11:18
  • It's not a 1:1 answer to the wording of your question, but I think the linked question will serve to achieve the general effect. In short, it suggests adding "tab guards" so if you tab into the one after the form (after the last field), it switches the focus to the first field. The tab guard before the form them focuses on the last field. So you would always go around in circles and you don't need to care about detecting if Shift is pressed or not. – VLAZ Dec 19 '18 at 11:21

1 Answers1

1

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>