0

I have a problem when trying to submit a form via a button defined in another form.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Test submit</title>
</head>
<body>
  <form id="dummyForm" name="dummyForm">
    <button onclick="sendTheForm();">Submit other form</button>
  </form>
  <form id="formID" name="formName" action="viewpost.php" method="POST">
    <input type="hidden" value="something" id="inputA1" name="inputA1" />
    <input type="hidden" value="something" id="inputA2" name="inputA2" />
  </form>
  <script type="text/javascript">
  function sendTheForm() {
    document.forms['formName'].submit();
  }
  </script>
</body>
</html>

The only way to achieve that redirect as expected is changing the following line:

onclick="sendTheForm();return false;"

I do not understand that the form submission works this way. Could anyone explain?

Thank in advance!

nhereveri
  • 151
  • 2
  • 9

2 Answers2

2
  1. You click the submit button
  2. The JavaScript event handler fires
  3. The other form starts to submit
  4. The submit button performs its default action
  5. The first form submits, cancelling the other form's submission process
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • The particular button is not the submit type, so I do not see why the dummy form submit trigger in the first place. **What is the default action of a button?** Answer: [Button Reference](http://w3c.github.io/html-reference/button.html) – nhereveri Jan 27 '15 at 01:32
  • @nhereveri — It **is** the submit type. The link you pointed at says: *A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"* – Quentin Jan 27 '15 at 10:32
  • Yes. I checked in step two, few minutes later. – nhereveri Jan 27 '15 at 20:49
0

I get the right answer from this post thanks to Quentin tips. Why submit trigger in the first place? Cause default type of a button it is a submit type, but different browsers use different default types. Check Button Reference.

Next line work as expected, without return false trick!

<button type="button" onclick="sendTheForm();">Submit other form</button>
Community
  • 1
  • 1
nhereveri
  • 151
  • 2
  • 9