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?
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?
Share Improve this question edited Aug 21, 2020 at 12:33 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 11, 2016 at 6:11 Joel MinJoel Min 3,4573 gold badges22 silver badges38 bronze badges 1- It happens on load, because you said it so, use onclick. – Bálint Commented May 11, 2016 at 6:13
4 Answers
Reset to default 7You 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);
});
Just change the file change event like this :
$('input[type=file]').change(function() { test() });
You're executing the function immedietaly instead of assigning a handler. You should instead do:
$('input[type=file]').change(test);
change takes function as argument, so you just need to provide function name to be called.
$('input[type=file]').change(test);