Dave Dave - 2 months ago 11
CSS Question

Dynamically Clone Element when User Specifies amount? - JavaScript + HTML

Is it possible for a user to type in an

<input>
box the amount of an element they would like to be cloned and append on the page?

The problem is, when a user currently specifies the amount of elements to be cloned, the number of elements is greater than that wanting to be cloned on the second click. Also, is it possible to hide the original element to be cloned within HTML and CSS? Please find attached the code below and the JsFiddle Link.



$("#btn").click(function() {
var number = document.getElementById("member").value;
var e = $('.col');
for (i=0;i<number;i++) {
e.clone().insertAfter(e);
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Specify Amount of Member Cards Required:<input placeholder="e.g. 2" type="text" id="member" name="member" value="">
<button id="btn" onclick="addinputFields()">Go</button>

<div>

</div>
<br>
<div class="col">Member Card</div>




Answer

Slight tweak on the HTML and Javascript.

Added a jsfiddle example of the code below.

HTML

Specify Amount of Member Cards Required:

<input placeholder="e.g. 2" type="text" id="member" name="member" value="">
<button id="btn">Go</button>

<div id="colTemplate" class="col">Member Card</div>
<div id="container"></div>

CSS

/* hide the template */
#colTemplate { opacity: 0; visibility: hidden; }

Javascript

$('#btn').click(() => {
  let number = document.getElementById('member').value,
      container = $('#container'),
      template = $('#colTemplate'),
      currentNumber = container.children().length;

  if (currentNumber < number) {
    // Add clones
    for (let i = 0; i < number - currentNumber; i++) {
      let clone = template.clone(true);
      clone.attr('id', null);   // Remove the id from the clone
      container.append(clone);
    }
  } else if (number < currentNumber) {
    // Remove extras
    let extras = $('#container .col');
    for (let i = currentNumber - 1; i > number - 1; i--) {
      extras.eq(i).remove();
    }
  }
});