Take focus on next input after key up using Jquery

2019-07-20 20:43发布

问题:

Note: My page has just textboxes. Nothing else. (nothing else => no other input types)

 $(":input[type='text']").keyup(function(event){

   if(valid)
     {
         // take a focus to next input element, which is again a text type.
     }

  });

How can i jump the focus to next input element after key up.

After Sarfraz Answer:-

 <div>
   <input type="text" maxlength="1" size="1" >
   <input type="text" maxlength="1" size="1" > 
   <input type="text" maxlength="1" size="1" > // sarfraj -- here it crash   Please check below for error.
 </div>


 <div>
   <input type="text" maxlength="1" size="1" >
   <input type="text" maxlength="1" size="1" >
   <input type="text" maxlength="1" size="1" >
 </div>

From firebug issue is

  $(this).next("[type=\"text\"]")[0] is undefined
  [Break On This Error] $(this).next('[type="text"]')[0].focus(); 

回答1:

Update:

Here is how you should modify your code:

$(":input[type='text']").keyup(function(event){
   if(valid) {
      if ($(this).next('[type="text"]').length > 0){
         $(this).next('[type="text"]')[0].focus();
      }
      else{
         if ($(this).parent().next().find('[type="text"]').length > 0){
            $(this).parent().next().find('[type="text"]')[0].focus();
         }
         else {
           alert('no more text input found !');
         }
      }

   }
});

How can i jump the focus to next input element after key up.

Use the next() with focus:

$(this).next('[type="text"]')[0].focus();

So here is how your code should look like:

$(":input[type='text']").keyup(function(event){
   if(valid) {
      $(this).next('[type="text"]')[0].focus();
   }
});


回答2:

The html tabindex property is used to define the order by which you move through the input elements if you hit tab. I would start by setting this.

So set the tab indexes then (to expand on your example):

 $(":input[type='text']").keyup(function(event){
   if(valid)
     {
         var currentIndex = $(this).attr("tabindex");
         var nextIndex = parseInt(currentIndex)+1;
         $("input[tabindex='"+nextIndex+"']").focus();
     }
  });

Basically get the tabindex of the current element, add 1, and get the element with that tab index.