user2781911
user2781911

Reputation: 79

TextInput automatically jump to another field once it has filled with certain criteria

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.

Upvotes: 1

Views: 1294

Answers (1)

Ashish Chopra
Ashish Chopra

Reputation: 1439

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;
        }
    }
}
}

Upvotes: 2

Related Questions