Search code examples
jqueryfocusonkeyup

Take focus on next input after key up using Jquery


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(); 

Solution

  • 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();
       }
    });