最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why submit() method didn't trigger onsubmit event? - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question asked Aug 13, 2017 at 18:46 blue catblue cat 1931 silver badge11 bronze badges 3
  • 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&#39;t need to call submit through javascript.w3schools./jsref/event_onsubmit.asp – Amit Kumar Singh Commented Aug 13, 2017 at 19:00
Add a ment  | 

2 Answers 2

Reset to default 6

Well, 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>
发布评论

评论列表(0)

  1. 暂无评论