Lloyd23
Lloyd23

Reputation: 11

How do I duplicate a form in a div when I press a button?

I have an already existing form in my code which includes 2 text fields and a submit button.
I have also added an “add” button which when clicked should add a new form below.How do I achieve this using Javascript.
How do I add a new form by clicking on the add button?

Upvotes: 0

Views: 1375

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48630

You could use a templating engine like {{ mustache }} to create a form template and inject an auto-incrementing ID into it.

Note: If you want more logic, customization, or compiled templates, you can use handlebars.

var FORM_ID_INCR = 1; // Ever-increasing couter

document.getElementById('add-form-btn').addEventListener('click', function(e) {
  createAndAppendNewContactForm();
});

function createAndAppendNewContactForm() {
  let viewModel = { formId : FORM_ID_INCR++ };
  let template = document.getElementById('form-template').innerHTML;
  let renderedHtml = Mustache.render(template, viewModel);
  let node = document.createRange().createContextualFragment(renderedHtml);
  document.getElementById('form-container').appendChild(node);
}
.form-field {
  margin-bottom: 0.5em;
}

.form-field label {
  display: inline-block;
  font-weight: bold;
  width: 6em;
}

.contact-form {
  border: 1px solid #DDD;
  padding: 0.5em;
  margin-bottom: 0.5em;
}

#form-container {
  margin-bottom: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.1.0/mustache.min.js"></script>
<script id="form-template" type="text/html">
  <form id="form-{{formId}}" class="contact-form">
    <h2>Form #{{formId}}</h2>
    <div class="form-field">
      <label>First Name</label>
      <input type="text" name="firstName"/>
    </div>
    <div class="form-field">
      <label>Last Name</label>
      <input type="text" name="lastName"/>
    </div>
    <input type="submit" />
  </form>
</script>
<body onload="createAndAppendNewContactForm()">
  <h1>Forms</h1>
  <div id="form-container"></div>
  <button id="add-form-btn">Add Form</button>
</body>

Upvotes: 0

BM2ilabs
BM2ilabs

Reputation: 532

you could use jquery $.clone() function so when you hit the button the form will be cloned and then $.append() to the parent div

this will clone the form with the data , if you want something without the data you should clone the form in the start of the script.

Upvotes: 1

Related Questions