I hope this question is not duplicated.
I have two HTML elements, one which when it's changed must populate the value of another via an async method named foo()
.
The following code works:
<input type="text" id="elem">
<input type="file" onchange="
(async ()=>{
document.getElementById('elem').value = await foo(this);
})()
">
The following one doesn't (no exception is thrown in console, and #elem
is not updated):
<input type="text" id="elem">
<input type="file" onchange="
async ()=>{
document.getElementById('elem').value = await foo(this);
}
">
Why the first example works and the second doesn't?
I hope this question is not duplicated.
I have two HTML elements, one which when it's changed must populate the value of another via an async method named foo()
.
The following code works:
<input type="text" id="elem">
<input type="file" onchange="
(async ()=>{
document.getElementById('elem').value = await foo(this);
})()
">
The following one doesn't (no exception is thrown in console, and #elem
is not updated):
<input type="text" id="elem">
<input type="file" onchange="
async ()=>{
document.getElementById('elem').value = await foo(this);
}
">
Why the first example works and the second doesn't?
Share Improve this question asked Jul 31, 2020 at 17:44 user8555937user8555937 2,4032 gold badges20 silver badges51 bronze badges 2- 1 The first snippet executes the method via the IIFE. The second one does not. – Taplar Commented Jul 31, 2020 at 17:48
- When you assign "onchange" in the attribute of the tag, as you're doing, you have to include the entire script, including the "()" to execute a function. If you were assigning it in a script, like "myinput.onchange = " and not in the tag, then you would just use the function name or the function definition. – Colin G Commented Jul 31, 2020 at 17:55
2 Answers
Reset to default 2(function() {...})()
This invokes the function.
it's like invoking a named function someFunction()
in your second example you're just creating a function without invoking it. it returns the function itself.
- invoking:
onchange='someFn()'; // calls function
- without invoking
onchange='someFn'; // returns function.
The first example is what is known as a self invoking function. This is why is is wrapped in () and is followed by () to call the function immediately.
The second answer isn't working because you are not actually calling it. Simply add "const myFunc = async () => {}" and call "myFunc" on the button click.