Joel Min Joel Min - 6 months ago 17
Javascript Question

Why is my JS function executed onload instead of onchange?

Here's the code:

window.onload = function() {
oldonload && oldonload();

function test() {
alert("meh");
}

$('input[type=file]').change(test());
}


The code is fairly straight forward,
test()
is called only when
input[type=file]
is changed. However
test()
is being called whenever my page is loaded.

What is going on here? How would I execute the function only when user interacts with the input element?

Answer

You are calling the method on this line:

$('input[type=file]').change(test());

Change it to:

$('input[type=file]').change(test);

If you want to pass a parameter to test:

var myVar = 5;
$('input[type=file]').change(function () {
   test(myVar); 
});