Take focus on next input after key up using Jquery

只谈情不闲聊 提交于 2019-12-11 02:53:47

问题


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.



来源:https://stackoverflow.com/questions/7217360/take-focus-on-next-input-after-key-up-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!