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>
100% working for up arrow
and down arrow
$(document).ready(function(eOuter) {
$('input').on('keydown', function(eInner) {
var keyValue = eInner.which; //enter key
if (keyValue == 40 || keyValue == 38){
var tabindex = $(this).attr('tabindex');
if(keyValue == 40){ //down arrow 40
tabindex++;
}else{ //up arrow 38
tabindex--;
}
$('[tabindex=' + tabindex + ']').focus();
}
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With