Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto tab to next input field when fill 4 characters

What I am trying to do is, point to next tab when filling four characters. Each field should have 4 characters and once it is completed it should move to next input box.

 $(".inputs").keyup(function () {         if (this.value.length == this.maxLength) {           $(this).next('.inputs').focus();         }   }); 

Fiddle.

like image 272
Prasanga Avatar asked May 27 '14 11:05

Prasanga


People also ask

How do you activate the next input field on Enter?

Pressing enter key should set focus to next text or numeric input field (product code or quantity), skipping buttons.


1 Answers

Your code works fine, however your input elements are set as type="number". Non-numeric content is ignored, so if you enter "abcd", for example, the input's value is empty (meaning a length of 0). If you enter "1234" on the other hand, the input's value is 1234.

If you want your code to fire when non-numeric content is entered, simply change each input's type to text.

<input class="inputs" type="text" maxlength="4" /> 

JSFiddle demo.

Note that I've also removed the duplicate class attribute from each of your elements in that example, too.


As krish has mentioned in the comments on your question, there is an issue with your code in that the last input element will continue to accept more than 4 characters. To fix this, put a check in place to ensure that there is a next('.inputs') element:

if (this.value.length == this.maxLength) {   var $next = $(this).next('.inputs');   if ($next.length)       $(this).next('.inputs').focus();   else       $(this).blur(); } 

JSFiddle demo.

like image 144
James Donnelly Avatar answered Oct 03 '22 15:10

James Donnelly