3

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?

blue cat
  • 173
  • 1
  • 11
  • 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 `` – Rahul Verma Aug 13 '17 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 Aug 13 '17 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.https://www.w3schools.com/jsref/event_onsubmit.asp – Amit Kumar Singh Aug 13 '17 at 19:00

2 Answers2

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'>
<input type='button'>
<button>

You likely don't need an onclick handler on that button at all

James
  • 20,957
  • 5
  • 26
  • 41
1

it seems that you can't, please check this post - https://stackoverflow.com/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>