Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 443
user3058870 Avatar asked Sep 27 '16 20:09

user3058870


2 Answers

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();
         }
     });
});
like image 146
SAKIB Avatar answered Sep 30 '22 06:09

SAKIB


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.

like image 24
adeneo Avatar answered Sep 30 '22 05:09

adeneo