user3058870 user3058870 - 2 months ago 11
jQuery Question

Tab to next tabindex field on down arrow key

I have a webform and want the users to be able to go to the next tabindex field when the down arrow is pressed (behave like the tab key). The following code works when enter key is pressed but if I change the keycode to 40 this code will not work for the down arrow key.

Any help greatly appreciated.

<div>
<input name="line[]" class="" type="text" tabindex="1"/>
</div>
<div>
<input name="line[]" class="" type="text" tabindex="2"/>
</div>
<div>
<input name="line[]" class="" type="text" tabindex="3"/>
</div>

//tab to next tabindex on enter key
<script>
var id;
$(document).ready(function(eOuter) {
$('input').bind('keypress', function(eInner) {
if (eInner.keyCode == 13){ //enter key
var tabindex = $(this).attr('tabindex');
tabindex++; //increment tabindex
$('[tabindex=' + tabindex + ']').focus();

$('#Msg').text($(this).attr('id') + " tabindex: " + tabindex + " next element: " + $('*').attr('tabindex').id);
}
});
});
</script>

Answer

The arrow keys don't fire consistently on the keypress event, you want to use keydown instead

$('input').on('keydown', function(eInner) {

    if (eInner.which === 40) { //arrow down

FIDDLE

Your message has some issues as well, the elements don't have ID's, jQuery's attr returns a primitive that has no id property etc.

Comments