I have two input elements, the first is focused, and I want to focus the second by simulating the TAB keypress/keydown event. (Note: I don’t want to use .next() or such.)
This is my code, inspired from this question:
$('input').first().focus();
var e = $.Event('keydown');
e.which = 9; // TAB
$(':focus').trigger(e);
Please see http://jsfiddle.net/3PcPH/
The code doesn’t work. What is wrong?
There is no simple programmatic way to do this using Javascript… so here’s a brute force way.
According to W3:
I accomplished this by storing the order of elements in the form that have
tabIndex > 0in their tabIndex order and then concatenating the rest of the elements in the order they appear within the document. The following code simulates a tab keypress when focused on a form input and the letter ‘z’ is pressed (but you can change this to whatever condition you require):See demo