I have a form like below:
<form action="/action_page.php" onsubmit="alert('The form was submitted');" >
Enter name: <input type="text" name="fname">
<input type="button" onclick="document.getElementsByTagName('form')[0].submit()" value="Submit">
</form>
Though I clicked the button and indeed it submitted the form, but the alert
box wasn't shown. That is, the submit()
method submitted the form but without triggering the onsubmit
event. What happened? And how should I use submit()
method to trigger the onsubmit
event?
I have a form like below:
<form action="/action_page.php" onsubmit="alert('The form was submitted');" >
Enter name: <input type="text" name="fname">
<input type="button" onclick="document.getElementsByTagName('form')[0].submit()" value="Submit">
</form>
Though I clicked the button and indeed it submitted the form, but the alert
box wasn't shown. That is, the submit()
method submitted the form but without triggering the onsubmit
event. What happened? And how should I use submit()
method to trigger the onsubmit
event?
-
1
You will need to add a input with type submit button and when you click on it then only your onsubmit will be auto triggered. add below element to your html and click on it
<input type="submit" value="Submit"/>
– Rahul Verma Commented Aug 13, 2017 at 18:53 -
btw you can simply use
document.forms[0]
or in the case of a form element as in your code,this.form
– inarilo Commented Aug 13, 2017 at 18:55 - Because its a button. It will fire onclick. In onclick, you submitted the form through javascript. You can try to change it to input type submit to see if there is any difference. In that case, you don't need to call submit through javascript.w3schools./jsref/event_onsubmit.asp – Amit Kumar Singh Commented Aug 13, 2017 at 19:00
2 Answers
Reset to default 6Well, the documentation for the submit method is pretty clear that it doesn't trigger onsubmit.
Since any of the following form elements cause a form submit:
<input type="submit">
<button>
<button type="submit">
You likely don't need an onclick handler on that button at all.
it seems that you can't, please check this post - https://stackoverflow./a/19847255/8449863
however, please try workaround with hidden submit button:
<form action="/action_page.php" onsubmit="alert('The form was submitted');" >
Enter name: <input type="text" name="fname">
<input type="button" value="Submit" onclick="document.getElementById('submit').click();" >
<input id="submit" type="submit" style="display: none;" />
</form>