I use jQuery to write a script that completely dynamically duplicates the contents of the HTML div, and then adds a button to delete the corresponding "new div". I mainly use this as a way to add more fields to the form. I would use an existing script, but all those there seem to only add input fields and are not very dynamic. That way, I can use the button to duplicate exactly what I want by adding it to HTML and NOT JavaScript.
Everything seems to work fine when it comes to duplicating the original contents of the container. The only thing I came across was assigning id to the delete button. In my example, the parent div of the “source content” is “links” ... so the first “new content” should have the identifier “links-1” ... which it does. When I create a delete button (depending on the contents of the div shown below), I want to change its id to “links-1”, and then when it clicks, it will remove the div of “new content” with the identifier “link-1”. With my current script, none of the properties of the delete button changes ...
Does anyone have any ideas?
HTML
<div id="references">
<input type="text" name="references[]" size="30" class="text-input" placeholder="Must contain a valid, working URL." style="position: relative;z-index: 0;">
</div>
<div id="more-references">
<-- Where to put the new content -->
</div>
<div id="remove-button" style="visibility: hidden;">
<-- The button that removes content --> <i class="fi-x"></i>
</div> <i class="fi-plus" rel="addMore" id="references"></i>
jQuery:
$(function(){
var i = 0;
var oldRemove = $('#remove-button');
$('[rel="addMore"]').on('click', function(){
i++;
var newRemove = oldRemove.clone();
var buttonID = $(this).attr("id");
var container = $('#' + buttonID + '-content');
var content = container.html();
var insertionPoint = $('#more-' + buttonID);
insertionPoint.append('<div id="' + buttonID + '-' + i + '">' + content + '</div>');
newRemove.prop('id', 'remove-' + buttonID + '-' + i);
insertionPoint.append(newRemove.html());
});
});
source
share