Question

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>
Était-ce utile?

La 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");
    });

Autres conseils

var temp = $(".addr:last").clone()
temp = $(temp).(':input').val('');
$(temp).attr('id', ++id).insertAfter(".addr:last");

Try to use $(".className").empty();

Remove all child nodes of the set of matched elements from the DOM

You can use the following to clean the fields inside DIV

$('.addr').find('input:text').val('');
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top