admin管理员组文章数量:1387332
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>
本文标签: javascriptWhy submit() method didn39t trigger onsubmit eventStack Overflow
版权声明:本文标题:javascript - Why submit() method didn't trigger onsubmit event? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744498010a2609147.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论