JSGarcia JSGarcia - 1 year ago 106
Javascript Question

Duplicate DOM node jQuery (not reference)

I am developing a dynamic form, and I need to duplicate a node and insert it into another DOM position.

My problem is that when I first copy the node (which contains empty inputs), I fill it with data, and I copy it again, it is copied with all the data.

I would like to duplicate the variable containing the empty DOM node and not refer to it.

It's possible?

var emptySegment = $( '#segment' ).clone();

$(document ).on('click', '#add', function(){
var emptySgmt = emptySegment; // Duplicate emptySegment.
emptySgmt.insertAfter( '.lastSegment' );

Thank you

Answer Source

After you clone the element you need to reset the input (or any other elements) back to the state you require. Try this:

$(document).on('click', '#add', function() {

function cloneSegment() {
    return $('#segment').clone().find('input').val('').end();

Note this example simply resets the value of all input elements within the segment. You can put your own logic in there to meet whatever your specific requirements are.