2

So I have this simple test case where a form cannot be submitted via jQuery when there is a button with type submit and an ID submit in the form.

If you change the ID to something else, jQuery can easily submit the form.

What is happening here?

$('#submitform').on('click', () => {
  $('form').submit();
});

$('form').on('submit', () => {
  alert('submit')
});
<!DOCTYPE HTML>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
  <button id="submitform">JS-Submit</button>
   

  <form action="#" id="validation" novalidate>

    <input type="text" name="someinput" />

    <!-- change ID to anything other than "submit" to be able to submit form via JS -->
    <button type="submit" id="submit">Submit</button>

  </form>
</body>
</html>
  • 4
    It's because the `id` attribute of child controls of the form become keys of the members of its object, hence the `submit` button becomes the `form.submit` property which overwrites the `form.submit()` function. See the duplicate I marked for more info. – Rory McCrossan Dec 13 '17 at 15:02
  • Thanks for the fast answer! After reading the duplicate I understand why this is problematic. – michaelworm Dec 13 '17 at 15:04

0 Answers0