Search code examples
jqueryformscloneinsertafter

jQuery: clone a div and insert it after last div with sequential id


I need to insert a clone of a div containing a form after the last div with that same class. But how can I empty all the form fields? I have the following code:

<span id="add">Add</span>
<div id="0" class="addr">
    <input type="text" name="a">
    <input type="text" name="b">
    <input type="text" name="c">
</div>
<script>
    jQuery(document).ready(function($){
        $('#add').on('click',function() {
            var id = $(".addr:last").attr('id');
            $(".addr:last").clone().attr('id', ++id).insertAfter(".addr:last");
        });
    });
</script>

Solution

  • Instead of cloning div, you can use html of that div to append it like this

    $('#add').on('click', function () {
            var id = $(".addr:last").attr('id');
            var appendDiv = jQuery($(".addr:last")[0].outerHTML);
                appendDiv.attr('id', ++id).insertAfter(".addr:last");
        });