0

I have a simple function, and need use the index from foreachloop, example:

window.onload = function()
{   
    Array.from(document.getElementsByClassName('image_add_product')).forEach(function(element,index)
    {
        element.addEventListener("change", input_change(index), false);
    });
};

And in input_change function i need the index

function input_change(index)
{
    alert(index);
    alert(this.type);
}

I dont know why, when window load, the change is automatic trigger! Even not change anything. See below:

window.onload = function()
{   
    Array.from(document.getElementsByClassName('image_add_product')).forEach(function(element,index)
    {
        element.addEventListener("change", input_change(index), false);
    });
};

function input_change(index)
{   
    alert(this.type);
    alert(index);
}
<input type="file" class="image_add_product">one
<input type="file" class="image_add_product">two
<input type="file" class="image_add_product">tree

Whats happens?

MagicHat
  • 379
  • 1
  • 6
  • 28
  • 1
    `element.addEventListener("change", function() { input_change(index); }, false);` (you're passing the result of the function call i.e. `undefined` but you're supposed to pass a function) –  Jan 20 '22 at 15:14
  • Duplicate: [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) –  Jan 20 '22 at 15:15
  • Tks for atention, exact answer @ChrisG – MagicHat Jan 20 '22 at 15:27

0 Answers0