5

I've got a problem: I'm building an in-page multistage form. Every 'stage' is on its own panel (a div). I'll move through panels via javascript (next/prev buttons). Every panel has its own validation, and it's not possibile to jump to the next panel if the current is not succefully validated. All fine.

The problem is when the user starts using tabs to jump from a field to another. When he reaches the last field of the current panel, the tab will bring him to the next panel.

So what I would need is to avoid the last field of each form to accept tab events, or, the first field of each form to be reachable from a tab. Or the like.

In other words: how disable tab key only for certain fields? Or, how to limit tab action only to a certain group of fields in a form?

I've tried a couple of ways, no luck:

// on last panel field
$('.block-tab').on('keypress', function(e) { 
  if (e.keyCode == 9) e.preventDefault();
});

// on first panel field
$('.block-tab').on('keyup', function(e) { 
  if (e.keyCode == 9) e.preventDefault(); 
});
Luca Reghellin
  • 7,426
  • 12
  • 73
  • 118
  • 3
    The third-one works: `onkeydown`. You can alternatively add [`tabindex`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex) attributes to form elements. – Teemu Jun 13 '18 at 14:32
  • [This other question](https://stackoverflow.com/questions/5192859/how-to-ignore-html-element-from-tabindex?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) suggests using `tab-index='1'` to prevent tabbing, if that's the route you're going down. – Lewis Jun 13 '18 at 14:39
  • @Lewis I don't think it'll work because then tab will jump to the next available field, won't it? – Luca Reghellin Jun 13 '18 at 14:44

1 Answers1

8

As suggested by @Teemu, onkeydown will work. So basically, on the last field of each panel/tab I'll assign a class such as 'block-tab'.

<input class="block-tab" name="email" id="email" type="text"  value="" />

Then:

$('.block-tab').on('keydown', function(e) { 
  if (e.keyCode == 9) e.preventDefault(); 
});

This will prevend the user to access the next panel without clicking the 'next' button and thus validating the current panel first.

Luca Reghellin
  • 7,426
  • 12
  • 73
  • 118