0

I'm developing a small system but I noticed that there is a difference in using a loop for var and let, normally i always use let anyway but i decided to do some checks with var and that blew me away.

Example:
This works:

var inp = document.getElementsByTagName('input');
var focus = 0;
var inpLen = inp.length - 1;
inp[focus].focus();

for (let i = 0; i < inp.length; i++) {
    const e = inp[i];

    e.onkeyup = function () {
        if (e.value.length == e.max) {

            var leap = Math.min(i + 1, inpLen);
            inp[leap].focus();
        }
    } 
}
<input type="number" max="2">
<input type="number" max="3">
<input type="number" max="2">
<input type="number" max="3">

And it doesn't work:

var inp = document.getElementsByTagName('input');
var focus = 0;
var inpLen = inp.length - 1;
inp[focus].focus();

for (var i = 0; i < inp.length; i++) {
    var e = inp[i];

    e.onkeyup = function () {
        if (e.value.length == e.max) {

            var leap = Math.min(i + 1, inpLen);
            inp[leap].focus();
        }
    } 
}
<input type="number" max="2">
<input type="number" max="3">
<input type="number" max="2">
<input type="number" max="3">

My question is:
Why this happens, and how can I set my loop with var to work correctly

Previell
  • 53
  • 7

0 Answers0