1

I want an input text that automatically jump to another input text field once it reach max value.

This is the example text field.

Identification card:
<input type="text" name="ic[1]" size="15" maxlength="6" pattern="[0-9]*" title="6 number only"> - 
<input type="text" name="ic[2]" size="15" maxlength="2" pattern="[0-9]*" title="2 number only"> - 
<input type="text" name="ic[3]" size="15" maxlength="4" pattern="[0-9]*" title="4 number only">

How to make the input text field jump to another field as soon as the first text field reached the max number? It's like when we input serial key during the installation of a software. If possible and if it required javascript, I want it in a simple javascript and not jquery.

user2781911
  • 79
  • 1
  • 2
  • 9
  • You just have to listen to the onKeyPress and check the length of the input value. If it reaches the size/limit, then focus on the next ``. – Terry Mar 16 '14 at 10:25
  • @Terry How to focus on the next input once it reach the limit size? – user2781911 Mar 16 '14 at 10:45

1 Answers1

2

No jQuery used and is a very clean implementation:

  • Reads from the maxlength attribute.
  • Scales to any number of inputs inside of your container.
  • Automatically finds the next input to focus.
  • No jQuery.

http://jsfiddle.net/4m5fg/5/

var container = document.getElementsByClassName("container")[0];
container.onkeyup = function(e) {
var target = e.srcElement;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
    var next = target;
    while (next = next.nextElementSibling) {
        if (next == null)
            break;
        if (next.tagName.toLowerCase() == "input") {
            next.focus();
            break;
        }
    }
}
}
Ashish Chopra
  • 1,413
  • 9
  • 23
  • Also see http://stackoverflow.com/questions/574941/best-way-to-track-onchange-as-you-type-in-input-type-text for other requirements of the textbox text changing other than typing. – Jono Mar 16 '14 at 10:28
  • @user2781911 Please accept answer if it suffice your need. :) – Ashish Chopra Mar 16 '14 at 10:32
  • @AshishChopra Thank you for your answer. I have tried the code in jsfiddle. Yet it doesn't fulfill my requirement for the input. It doesn't automatically jump to another field when it reach max length. – user2781911 Mar 16 '14 at 10:38
  • @user2781911 I tried and it's working in `Firefox` I'll check in other browsers and will update you on that. – Ashish Chopra Mar 16 '14 at 10:42
  • @AshishChopra I use Firefox currently. It doesn't work when I test in jsfiddle. I don't know what the problem is. I will try in my code and will update you after this. – user2781911 Mar 16 '14 at 10:47