-2

I'm creating a huge form wizard with many input fields. The fields are inside sections that have display: none; and by clicking a button I'm walking through the sections and at the end I'm submitting the form. Inside one section there is another form to upload an image via ajax. To use ajax I need to prevent the form from being submitted with event.preventDefault(); But this causes submitting the parental form. How can I prevent the parental form from being submitted, too? The html structure looks like this:

<form action="" id="wizard">
  <section id="sec1"></section>
  <section id="sec2">
    <form id="ajaxform">
      <input type="file" id="ajaxfile">
      <input type="submit" value="upload">
    </form>
  </section>
  <section id="sec3"></section>
  <button type="button">Back</button>
  <button type="button">Next</button>
</form>

The jQuery looks like this:

$(document).ready(function() {
   $('#ajaxform').submit(function(e) {
      e.preventDefault();
      $.ajax({stuff...});
   });
});
PhilHarmonie
  • 315
  • 1
  • 4
  • 15

1 Answers1

5

event.preventDefault() prevents the default behaviour of the event but does not stop it from bubbling up to other elements. Use event.stopPropagation():

Prevents further propagation of the current event in the capturing and bubbling phases.


Forms should not be nested. The behaviour of such invalid markup is not specified. You should fix the markup.

If, for some reason, you cannot alter the markup then you could use the submit event for the outer form and check for the presence of some value(s) to allow, or disallow, the submission. For example, have a hidden value in the last section that you only change when they reach the section (when it is shown).

Andy G
  • 18,518
  • 5
  • 42
  • 63
  • Thank you for your reply. Using `event.stopPropagation();` still submits the parental form. – PhilHarmonie Dec 28 '17 at 16:06
  • @PhilHarmonie I suspect that's because there really is only one `
    ` in the actual DOM, because the browser will ignore the inner `
    `.
    – Pointy Dec 28 '17 at 16:13