[Fixed]-Keep a copy of a clean HTML element for later cloning using jQuery in a right way

1πŸ‘

βœ…

In your current code, you only clone from the original form once, later in your addForm, you just keep altering the same cloned element and insert it, and insert same element to same place won’t have any effect.

What you should do is:

  1. Get the reference of the target element. You can clone it here if the referenced element will also be altered, and you want to keep the clone template clean, but it’s not a must do.

  2. When you call addForm, clone from that referenced target element, alter the cloned one, and insert.

$(document).ready(function() {
    // Get the reference as template.
    var $original_form = $('.dynamic-form');

    function addForm() {
        var formCount = parseInt($('#total-forms').val());
      
        // Clone to get a new element when we really need one.
        var $new_form = $original_form.clone(true);
        $new_form.find('input').val(formCount + 1);
        $new_form.insertAfter($('.dynamic-form:last'));
        $('#total-forms').val(formCount + 1);
        return false;
    }

    $(function () {
        $('.add-row').click(function() {
            return addForm();
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='total-forms' type='hidden' value='1'>
<div class='dynamic-form'>  
    <input value='1'>
</div>
<button class='add-row'>Add Row</button>
πŸ‘€fuyushimoya

0πŸ‘

You are not saving a copy of the original form, rather, you are creating one clone that is saved to the original_form variable. To get a new clone each time, you need to save the original form in its own variable, and then each time you want a clone, call the clone function on it. Where you have

var original_form = $('.dynamic-form').clone(true).get(0);

Instead just save the $(β€˜.dynamic-form’) and each time you need to retrieve a clone, call the clone function.

πŸ‘€PJ K

0πŸ‘

You can add dynamic row in a more simpler way:

$(document).ready(function() {       
$('.add-row').click(function() {
        var value=parseInt($('.dynamic-form input:last').val())+1;
        var newRow= '<br/><input value='+value+'>';
        $('.dynamic-form').append(newRow);
    });    
});

Leave a comment