Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus the next input with down arrow key (as with the tab key)

Tags:

javascript

I have a huge entry form and fields for the users to input.

In the form user use tab key to move to next feild,there are some hidden fields and readonly textboxes in between on which tab key is disabled using javascript.

Now users finds difficult to use tab key and wants same functionality on down arrow key of the keyboard.

I was using the below code to invoke the tab key code on js but not working,please some body help me on this.

function handleKeyDownEvent(eventRef)
{ 
 var charCode = (window.event) ? eventRef.keyCode : eventRef.which;

 //alert(charCode);

 // Arrow keys (37:left, 38:up, 39:right, 40:down)...
 if (  (charCode == 40) )
 {

  if ( window.event )
   window.event.keyCode = 9;
  else
   event.which = 9;

  return false;
 }

 return true;
}

<input type="text"   onkeydown=" return  handleKeyDownEvent(event);" >
like image 220
lakshmi kanth Avatar asked Sep 13 '12 13:09

lakshmi kanth


People also ask

What are the 4 arrow keys?

Alternatively referred to as cursor keys, direction keys, and navigation keys, the arrow keys are usually located between the standard section and the numeric pad on computer keyboards. It is made up of four keys: the left arrow (back arrow), up arrow, down arrow, and the right arrow (forward arrow).

How do you navigate with arrow keys?

Arrow keys - Using the arrow keys on the keyboard, move the cursor up, down, left, or right in the document. Ctrl and Arrow keys - Holding down the Ctrl key while pressing the left or right arrow keys moves the cursor one word at a time. Using this shortcut is much faster than only using the arrow keys.


1 Answers

Using jQuery, you can do this :

$('input, select').keydown(function(e) {
    if (e.keyCode==40) {
        $(this).next('input, select').focus();
    }
});

When you press the down arrow key (keyCode 40), the next input receives the focus.

DEMO​

EDIT :

In Vanilla JS, this could be done like this :

function doThing(inputs) {    
    for (var i=0; i<inputs.length; i++) {
        inputs[i].onkeydown = function(e) {
            if (e.keyCode==40) {
                var node = this.nextSibling;
                while (node) {
                    console.log(node.tagName);
                    if (node.tagName=='INPUT' || node.tagName=='SELECT') {
                        node.focus();
                        break;
                    }
                    node = node.nextSibling;                
                }
            }
        };
    };
}
doThing(document.getElementsByTagName('input'));
doThing(document.getElementsByTagName('select'));

Note that you'd probably want to map the up key too, and go to first input at last one, etc. I let you handle the details depending on your exact requirements.

like image 52
Denys Séguret Avatar answered Sep 19 '22 08:09

Denys Séguret