0

Hello this is my for loop to create a table. Inside this table there are different function.

for (var id_day = 1; id_day < 32; id_day++)
{
    var tr = document.createElement("tr");  

    for (var i = 0; i < 3; i++)
    {
        var td = document.createElement("td");

        if (i == 0)
            td.innerHTML = id_day;
        if (i == 1)
        {
            var element = document.createElement("input");
            element.type = "text";
            element.id = "quantity_delivered_" + id_day;
            element.name = "quantity_delivered";
            element.value = "0.00";
            element.onchange = function(){update_input_detail(this.id, this.value, id_day, id_ddt, id_product);};
            td.appendChild(element);
        }
        if (i == 2)
        {
            var element = document.createElement("input");
            element.type = "text";
            element.id = "quantity_returned_" + id_day;
            element.name = "quantity_returned";
            element.value = "0.00";
            element.onchange = function(){update_input_detail(this.id, this.value, id_day, id_ddt, id_product);};
            td.appendChild(element);
        }

        tr.appendChild(td);
    }

    tbody.appendChild(tr);
}

Inside .onchange function id_day is always the last index 32 but i need that id_day is a different number for each function.

dhilmathy
  • 2,800
  • 2
  • 21
  • 29

1 Answers1

0

id_day is always 32 as by the time onchange is called the loop has finished and set id_day++ 32 times.

A quick fix would be to replace var with let in

for (let id_day = 1; id_day < 32; id_day++) {

but refactoring the code to remove the inlined functions would make it easier to read and have the side effect of making the scope changes clearer

Ross Mackay
  • 940
  • 4
  • 10