I am creating dynamic inputs in a for loop. Each input has its own onchange
function which checks if its value is bigger than array value. In every onchange
function, arrId
variable is always 6
which is the last element in the array.
Is there any possibility to make it correct? If lets say I change first input, arrId
should be the first element in the array, not the last element. But arrId
is always the last element in the array.
var arr = ["22", "12", "15", "6"];
for (var i = 0; i < arr.length; i++) {
var arrId = arr[i];
var input = document.createElement("input");
input.value = 0;
input.type = "number";
input.onchange = function(x) {
console.log(x.target.value + " " + arrId);
if (parseInt(x.target.value) > parseInt(arrId)) {
x.target.value = arrId;
}
}
document.getElementById("inputs").appendChild(input);
}
input {
display: block;
margin: 10px 0;
}
<div id="inputs">
</div>