Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  88] [ 1]  / answers: 1 / hits: 112880  / 11 Years ago, sun, march 24, 2013, 12:00:00

How can I focus the next input once the previous input has reached its maxlength value?



a: <input type=text maxlength=5 />
b: <input type=text maxlength=5 />
c: <input type=text maxlength=5 />


If a user pastes text that is greater than the maxlength, ideally it should spill into the next input.



jsFiddle: http://jsfiddle.net/4m5fg/1/



I must stress that I do not want to use a plugin, as I'd much rather learn the logic behind this, than use something that already exists. Thanks for understanding.


More From » jquery

 Answers
36

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/



<div class=container>
a: <input type=text maxlength=5 />
b: <input type=text maxlength=5 />
c: <input type=text maxlength=5 />
</div>


..



var container = document.getElementsByClassName(container)[0];
container.onkeyup = function(e) {
var target = e.srcElement || e.target;
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;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (myLength === 0) {
var previous = target;
while (previous = previous.previousElementSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === input) {
previous.focus();
break;
}
}
}
}

[#79396] Friday, March 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
corie

Total Points: 371
Total Questions: 110
Total Answers: 113

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
;