dzjustinli2 dzjustinli2 - 5 months ago 12
Javascript Question

for onclick, when to use `onclick="confirmOnSubmit()` vs `onclick="confirmOnSubmit`

I'm very new to html and javascript. I have seen

onclick
been assigned to function with following parentheses
onclick="confirmOnSubmit()
and functions without following parentheses
onclick="confirmOnSubmit
. I was just wondering what is the difference between the two? When should I use one over the other? Thanks in advance for any help!

<input type="submit" value="Submit" id="submitID" onclick="confirmOnSubmit()"/>

Answer

using parentheses after a function name means invoking that function.However, using it without a parentheses just means the function itself.

<input type="submit" value="Submit" id="submitID" onclick="confirmOnSubmit()"/>

so in your example, it is basically saying that whenever the submit btn is clicked, invoke the confirmOnSubmit function.

<input type="submit" value="Submit" id="submitID"/>

document.getElementById('submitID').onclick=confirmOnSubmit 

however, in the above example, we don't want to call the function at that moment, we just want to assign a reference, so that it can be called later on when the event happens.

hope it helps.