Adding more fields to a form

I’m trying to create an “add more” feature to a web form, using something @PaulOB showed a few years ago. However, whenever the button is pressed it tries to submit the form despite having preventDefault(). I’m using the add more on a date field rather than a file field but I don’t think that should make any difference? It seems to be okay if I put the code into Codepen but then I guess Codepen doesn’t do a form submit.

This is my js:

const addMore = document.querySelector(".add-more");
let fInput = document.querySelector(".more-date");

addMore.addEventListener("click", function (e) {
  e.preventDefault();
  let newFInput = fInput.cloneNode();
  fInput.parentNode.insertBefore(newFInput, fInput.nextSibling);
  fInput = newFInput;
});

Voila my HTML form (part thereof):

<form method="post"
  <div class="field">
    <label for="event">Event:</label>
    <input type="text" name="event">
  </div>
  <div class="field">
    <label for="date">Date:</label>
    <input type="date" name="date[]" class="more-date" required>
  </div>
  <div>
    <button class="add-more">Add date...</button>
  </div>
  <input type="submit" value="Make Booking">
</form>
1 Like

Codepen should attempt a form submit if one were called for… (but it shouldnt be; a normal “button” should not trigger a submit event.)

Have you sniffed the button with browser inspector to see if anything else has latched a click event onto it that you weren’t expecting?

Ah-ha. It looks like I was missing a little line

<script src="js/addMore.js"></script>

:blush:

3 Likes

Hi,

I think the button is located insider the form element and causing it to act as a submit button by default. To get out of this, you can change type of “Add date…” button from “submit” to “button”. This can be done by adding the “type” attribute to the button element and setting its value to “button”.

Use this updated HTML code for the button:

<button class="add-more" type="button">Add date...</button>

With this change, clicking the “Add date…” button should no longer submit the form.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.