Skip to content
Advertisement

JQuery .append() content won’t stay on screen

I’m creating a form where the user can add their modules that they study at university. When they click the button, it adds a new set of fields for another module. I’ve added a click listener to the button #add and I’m trying to append the form #input_form with the same fields:

<form id="input_form">

   <h6>Add modules below...</h6>

   <div class="form-row">

      <div class="col-md-6">
         <input type="text" class="form-control" name="module_name" placeholder="Module Name">
      </div>

      <div class="col-md-6">
          <input type="text" class="form-control" name="module_code" placeholder="Module Code">
      </div>

    </div>

    <div class="form-group col-md-6">
        <label for="credit_entry"># of Credits: </label>
        <input type="number" name="credits" id="credit_entry">
    </div>

    <div class="form-group col-md-6">
        <label for="colour_selector">(Optional) Choose a Colour: </label>
           <select id="colour_selector" name="colour_select">
             <option value="blue">Blue</option> <!-- Default -->
             <option value="red">Red</option>
             <option value="yellow">Yellow</option>
             <option value="pink">Pink</option>
             <option value="black">Black</option>
            </select>
        </div>
     </div>

        <div class="row">
          <button name="add" id="add" class="btn btn-secondary">Add Another</button>
        </div>
 // Add fields dynamically
  $("#add").click(function() {
    $("#input_form").append("<h1>The fields will go here</h1>");
  });

When I click the button, I see the content (the h1) added for a split second but then it disappears. I am not sure why the appended HTML won’t stay on screen. I have another part of this project which works similarly and appends to a ul list and the HTML is persisting on screen for that just fine, but for some reason this won’t.

I’m pretty new to web design and jQuery so sorry if there’s an easy answer that I’m missing.

Advertisement

Answer

“If the element has a form owner, the element must submit the form owner from the button element.” (w3.org)

That means, any button inside a form executes submit() on its parent form. To prevent that, explicitly define the button type as button:

<button name="add" type="button" id="add" class="btn btn-secondary">Add Another</button>

In action: https://codepen.io/akamichael/pen/NWqgaWz?editors=1010

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement