views:

379

answers:

3

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.

+1  A: 

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.

Teja Kantamneni
I would do it this way if it was a semi static page, but I'm intending on writing a plugin so this functionality can be reused on any site. Working out the tab indexes for the page and trying to work in the (dynamically created) buttons without screwing up any other forms could be a major headache! Do you know of way to do this programmatically
Rowan
A: 

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!

Rowan
This isn't part of the W3C specification for the tabindex property and it's also not in the Mozilla Developer Center docs so it might only work in IE. See my answer for the link to the spec.
Andy E
+1  A: 

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!" />

However, this isn't part of the W3C specification for tabindex, which only allows an integer between 0 and 32767.

The easiest method I can think of in other browsers 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.

Andy E
I think I got there the same time as you! No, it's not a W3C specification but it works in firefox, safari, IE (and still validates as I'm setting the negative index programmatically). Thanks anyway +1
Rowan
Glad to hear it works in those. I checked after writing my answer and it worked in Chrome (which I would expect if it works in Safari).
Andy E