0

I am working with a django project, and part of the requirement is to have a button on the html page which when clicked clones a particular div and appends it to the bottom of the page as shown in the screenshot: Screenshot of the Page

I was successful in doing this applying the following code:

 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('input:text').val('') //Clear the Input fields of the cloned DIV        
        document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
        window.scrollTo(0,document.body.scrollHeight);

    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:0px;clear:both"></div>
<div style="float:right">

    <span class="label label-primary" id="add_cp_button" style="cursor: pointer;" onclick="addVL()">+ Add VL </span>

</div>
<div style="height:0px;clear:both"></div>
<div>
    <div id="ext_int_div_1">
        <div class="section">

            <fieldset class="scheduler-border">
                <legend class="scheduler-border">External Interface 1</legend>
                <div   class="sectionContent" style="border:0px solid grey;width:75%">
                    <div style="height:15px;clear:both"></div>

                    <div class="form-group">
                        <div class="col-sm-4">
                            <label>Name</label>
                        </div>
                        <div class="col-sm-8">
                            <input type="text" class="form-control"   name="vl_name_1" id="vl_name_1" placeholder="Name"/>
                        </div>
                    </div>
                    <div style="height:15px;clear:both"></div>

                    <div class="form-group">
                        <div class="col-sm-4">
                            <label>Connectivity Type</label>
                        </div>
                        <div class="col-sm-8">
                            <select class="form-control" name="vl_connectivity_type_1" id="vl_connectivity_type_1">
                                <option value="VIRTIO">VIRTIO</option>
                                <option value="">None</option>
                            </select>

                        </div>
                    </div>
                    <div style="height:15px;clear:both"></div>

                    <div class="form-group">
                        <div class="col-sm-4">
                            <label>Connection point Ref</label>
                        </div>
                        <div class="col-sm-8">
                            <select class="form-control" name="vl_con_ref_1" id="vl_con_ref_1" />
                            </select>
                        </div>
                    </div>
                    <div style="height:15px;clear:both"></div>

                </div>
            </fieldset>
            <div style="height:2px;clear:both;"></div>

        </div>
    </div>
</div>


<input type="hidden" name="vl_count" id="vl_count" value="1" />

Now i have a new issue, i need to make sure that the ID's of the elements withing the DIV are unique too, for example the the ID = "vl_name_1" for the first input box must be changed to "vl_name_2" when creating the creating the clone.

I tried the following example and added the snipped within my addVL() function just to see if any changes happen to my div's:

$("#ext_int_div_1").clone(false).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + clone.id); });

However, the above code got me nothing ( i am pretty sure the above piece of code is rubbish since i have no clue what it is doing).

Help appreciated here. Thank you

Community
  • 1
  • 1
Wilbur Dsouza
  • 127
  • 1
  • 10
  • Why do you need to change the ID's? If we know why, maybe there is a better way to do it? – Ian May 10 '17 at 08:47
  • @Ian because you can't have duplicate IDs ( not recommended ) – Mihai T May 10 '17 at 08:52
  • @MihaiT What I was getting at is maybe it's not worth using ID's in this instance. – Ian May 10 '17 at 08:55
  • @Ian 1) Just to add, this data is sent back via a submit form and i need to parse the response. 2) The reason for uniqueID's is to parse the response in the backend. I use django, and since the id's are all the same if i try "request.POST.get('vl_connectivity_type_1', '')" i always get the first div's values – Wilbur Dsouza May 10 '17 at 09:16

2 Answers2

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
  • 556
  • 1
  • 8
  • 16
  • This code works fine, but doesn't serve my purpose since a part of the id "input_" is hardcoded. In my case i cannot use this since my ID's can be random, i just need to replace the _0 with _1 and so forth, if that makes sense – Wilbur Dsouza May 10 '17 at 09:35
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
  • 127
  • 1
  • 10