[Fixed]-Cloning a div and changing the id's of all the elements of the cloned divs

0๐Ÿ‘

โœ…

I did the following and solved my problem:

var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
    function addVL(){
        var clone = original_external_int_div.cloneNode(true); // "deep" clone
        clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
        original_external_int_div.parentNode.append(clone);
        var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
        cloneNode.innerText = "External Interface "+vl_cnt;  //Change the Header of the Cloned DIV
        $(clone).find("*[id]").each(function(){
           $(this).val('');
           var tID = $(this).attr("id");
           var idArray = tID.split("_");
           var idArrayLength = idArray.length;
           var newId = tID.replace(idArray[idArrayLength-1], vl_cnt);
           $(this).attr('id', newId);
        });
        document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
        window.scrollTo(0,document.body.scrollHeight);

Thank you @ProblemChild for giving me the pointer in the right direction, I cannot upvote @ProblemChild for providing partial solution.

๐Ÿ‘คWilbur Dsouza

1๐Ÿ‘

I hope the snippet below helps.

$(document).ready(function () { 
  $sharerCount = 1;

  $('#addSharer').click(function() {
    if($sharerCount < 5) {
      $('#sharer_0').clone().attr('id', 'sharer_' + $sharerCount).insertAfter('.sharers:last').find("*[id]").attr('id', 'input_' + $sharerCount).val("").clone().end();
      $sharerCount += 1;
    }
    else {
      $('#addSharer').prop('disabled', 'true');
    }
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="form">
  <div class="form-group">
    <label class="control-label col-sm-3 col-xs-12">Share With<span class="red-text">*</span></label>

    <div class="col-sm-9 col-xs-12">
      <div id="sharer_0" class="field-group sharers">
        <input id="input_0" type="text" class="form-control field-sm">
      </div>
    </div>
  </div>

  <div class="form-group"> 
    <div class="col-sm-offset-3 col-sm-9 col-xs-12">
      <button id="addSharer" type="button" class="btn btn-success">Add Another</button>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
๐Ÿ‘คProblemChild

Leave a comment