Dave Dave - 1 year ago 112
CSS Question

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

Is it possible for a user to type in an

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++) {

<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 class="col">Member Card</div>

Answer Source

Slight tweak on the HTML and Javascript.

Added a jsfiddle example of the code below.


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>


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


$('#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
  } else if (number < currentNumber) {
    // Remove extras
    let extras = $('#container .col');
    for (let i = currentNumber - 1; i > number - 1; i--) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download