This is my first post.
I've been working on a Chrome Extension and yesterday I came across this problem. I already solved it, I just don't quite understand why it works this way. So if anyone can explain it, thank you!
So, in my popup.html I have a form with a submit button (and in popup.js some checkboxes may be generated dinamically inside this form):
<div>
<form id="confirmation">
<div id="ing"></div>
<div id="meth"></div>
<button id="check" type="submit">Submit</button>
</form>
</div>
Inside the script, I have this code, and it works fine so far:
let form = document.getElementById("confirmation");
form.onsubmit = () => {window.alert("submited")};
The problem was that before I had this, which triggered the Alert when I clicked the extension Icon, without the form being submitted:
let form = document.getElementById("confirmation");
form.addEventListener("submit", window.alert("submited"));
Why does it behave like that?
I'm fairly new to programming.
Cheers from Portugal!
Thats because the second parameter is a callback and you are simply calling the function.
This passes the return value of window.alert("submited")
as the second parameter
form.addEventListener("submit", window.alert("submited"));
This would pass a function that when called will trigger the window.alert
form.addEventListener("submit", () => { window.alert("submited") });