0

I try to make form where enter in fields does not submit form, so I tried disable submitting with onsubmit="return false;", but then <button type="submit"> would disabled too. So I tried to POST through javascript, like that:

<!DOCTYPE html>
<html>
<head>
  <title>test</title>
</head>
<body>
  <form method="post" onsubmit="return false;" name="form">
    <input type="text" name="foo">
    <input type="text" name="bar">
    <button onclick="submitForm()" name="btn" value="one">one way</button>
    <button onclick="submitForm()" name="btn" value="another">another</button>
  </form>

  <script type="text/javascript">
    function submitForm(argument) {
      document.form.submit();
    }
  </script>

</body>
</html>

Problems now:

  • clicking on button submits form, but does not include values of button
  • enter in text inputs submits again the form

In submitting function I could set some form value depending clicked button, but is there better way? And still, submitting with enter is not disabled.

How is best way to reach both goals?

PS! I am aware of Prevent users from submitting a form by hitting Enter and part of my example is inspired from one solution there. My example should show other problems too.

Community
  • 1
  • 1
w.k
  • 8,218
  • 4
  • 32
  • 55
  • General hint: If you have jQuery you actually *never* want to use inline event handlers (like `onsubmit="..."`, `onclick="..."`) anywhere. – Tomalak Dec 07 '16 at 13:15
  • @Tomalak, OK, including jquery is not big issue, but looked for vanilla solution too. – w.k Dec 07 '16 at 13:20
  • But your question is tagged [jquery] - and if you have that in your page anyway then there is no point using "vanilla". Besides, event handlers are no longer supposed to be attached this way in vanilla HTML+JS either. See http://caniuse.com/#feat=addeventlistener – Tomalak Dec 07 '16 at 13:24
  • @Tomalak , thank you, seems I am from stone age here, was not aware of this development. – w.k Dec 07 '16 at 13:34
  • It's a good idea to try and keep your HTML completely separate from any JS code. – Tomalak Dec 07 '16 at 13:43

0 Answers0