Rowan
Rowan

Reputation: 5727

jQuery / Javascript pass focus to next element while tabbing through page

I'm building a 'tag input' plugin with jQuery at the moment and I've hit a small stumbling block.

I'm adding a button after a text input in a form, and using javascript to provide functionality for the button. When the button is clicked (or return is pressed in the input), the value of the input is added to a list of tags. The input is then cleared and refocused.

My problem occurs when I tab through the interface, the button after the input gains focus when you tab to it but I want to cancel this behaviour. I could just blur the button but I'd rather the button passes focus to the next focusable element.

e.g. I have three inputs in my form: text-input-1, button, text-input-2. When text-input-1 is focused and I press tab, I want focus to jump to text-input-2 rather than the button.

Can this be done? Thanks in advance.

Upvotes: 1

Views: 1525

Answers (3)

Andy E
Andy E

Reputation: 344575

This is easy enough in IE, which accepts a negative integer for the tabIndex property which will remove it from the tabbing order:

<input type="button" tabindex="-1" value="Can't tab to me!" />

This isn't part of the HTML 4.01 specification for tabindex, which only allows an integer between 0 and 32767. However, it is specified in the HTML 5 drafts and supported in most major browsers.

The easiest method I can think of in browsers that don't support it would be to wait for the input's onkeydown event and check for the tab key. If the tab key is pressed, disable the button and set a timeout with an interval length of 0 to enable the button again.

Upvotes: 4

Rowan
Rowan

Reputation: 5727

Ah, I've answered my own question with help from Teja (+1).

All I needed to do was apply a negative tab index to the button!

Upvotes: 0

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

Change the tab index order, give text-input-1 tabindex to 100 and text-input-2 to 200 and for the button any number greater than 200. It should solve the problem.

Upvotes: 1

Related Questions