Intercepting keystrokes and changing focus in jQuery

I have a list div.boxinput(each with two input fields). If the down arrow key is pressed, I need to change the focus of another input.

I can intercept the key, but I cannot move the focus to another input.

 $(document).keydown(function(e) {
       e.preventDefault();
       if (e.keyCode == 40) { 
         alert("down"); 

          // find where is the focus ? 
           var hasFocus = $('input').is(':focus');
           alert(hasFocus);


         // change focus ( problem here, don't change focus )
         if ( $(hasFocus).parent().hasClass("reso") ) {
             $(hasFocus).parent().prev().find("input").focus();
          }else{
             $(hasFocus).parent().next().find("input").focus();
          }

      }     

       if (e.keyCode == 37) { alert("left"); }
       if (e.keyCode == 38) { alert("top"); }
       if (e.keyCode == 39) { alert("right"); }
});

I create my experiment here: jsfiddle.net/andreaferri/mt95g9cu/7/

How to choose an element with focus?

+4
source share
1 answer

So, here is a script that changes focus.

var focused;
$('input').focus(function() {
          focused = $(this);
}); 
$(document).keydown(function(e) {
    e.preventDefault();
    if (e.keyCode == 40) { 
       if ( $(focused).parent().hasClass("reso") ) {
          $(focused).parent().prev().find("input").focus();
       } else {
          $(focused).parent().next().find("input").focus();
       }
    }               
});

As you can see, you should get an object like this (this is the part where I specified the targeted input that you see?):

var focused;
$('input').focus(function() {
   focused = $(this);
}); 

, jsFiddle. , , , . , , . , , , . , , .

0

All Articles