John
John

Reputation: 227

Duplicate Div With New ID

I got a function that duplicates a div and increases the new div's id by 1

function duplicate(){
    // Get content to clone
    var line_to_clone = $('#fields_1').html();
    // Get new line id
    var next_line_id = $('.items').length + 1;
    // Add the div container
    var line_to_clone = '<div id="fields_' + next_line_id + '" class="items">' + line_to_clone + '</div>';
    // Create new line
    var new_line = line_to_clone.replace(/_1/gi, "_" + next_line_id);
    // Render it
    $('#renderer').append(new_line);
}

It will work but the ids are wrong when it hits 10

<div id="fields_8" class="items">
<div id="fields_9" class="items">
<div id="fields_100" class="items">
<div id="fields_111" class="items">
<div id="fields_122" class="items">
<div id="fields_133" class="items">
<div id="fields_144" class="items">

Upvotes: 0

Views: 108

Answers (2)

Mi-Creativity
Mi-Creativity

Reputation: 9664

Alternatively you can make use of jQuery .clone() function, also getting the id of the last item using jQuery :last selector then increase it by one before appending the html of the new item, like this:

jsFiddle 1

$('#btn-foo').on('click', function() {
  var lastItem = $('#renderer .items:last'),
    lastID = parseInt(lastItem.attr('id').replace('fields_', ''));
  $('#renderer').append(lastItem.clone().attr('id', "fields_" + (lastID + 1)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn-foo">Add</button>
<hr>
<div id="renderer">
  <div id="fields_1" class="items"><span>Lorem ipsum dolor sit amet.</span>
  </div>
</div>


Updated:

Upon a comment from the OP, there're issues of duplicating the values of input fields, also the values of id and name attributes must be unique, therefore, in this jsFiddle 2 we have them all fixed

Upvotes: 1

Mohit Tanwani
Mohit Tanwani

Reputation: 6638

Please check below snippet.

function duplicate(){
// Get content to clone
var line_to_clone = $('#fields_1').html();
// Get new line id
var next_line_id = $('.items').length + 1;
  
// Add the div container
var line_to_clone = '<div id="fields_' + next_line_id + '" class="items">' + line_to_clone + '</div>';
// Create new line

// Render it
$('#renderer').append(line_to_clone);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="renderer">
  <div id="fields_1" class="items">123</div>
</div>
<input type="button" value="add" onclick="duplicate()"/>

Upvotes: 1

Related Questions