jquery - How do I clone a div contains multiple input fields more than once? -


i have read few solutions in here still not figure out why div refuse clone more once.

here html:

<h4 class="ui dividing header">maklumat ahli keluarga</h4>     <div class="input_fields_wrap">         <button class="add_field_button">add more fields</button>         <div class="ahli_keluarga" id="ahli_keluarga1">             <div class="field">                 <label>nama</label>                    <div class="field">                    <input type="text" name="shipping[first-name]" placeholder="nama penuh">                    </div>             </div>         </div>     </div> 

here script:

<script type="text/javascript"> $(document).ready(function() {     var max_fields      = 10; //maximum div allowed     var wrapper         = $(".input_fields_wrap"); //fields wrapper     var add_button      = $(".add_field_button"); //add button id     var clone           = $( ".ahli_keluarga:first").clone().append('<a href="#" class="remove_field">remove</a>');      var x = 1; //initlal div count     $(add_button).click(function(e){ //on add input button click         e.preventdefault();         if(x < max_fields){ //max div allowed             x++; //div increment             $(wrapper).append(clone); //         }     });      $(wrapper).on("click",".remove_field", function(e){ //user click on remove text         e.preventdefault(); $(this).parent('div').remove(); x--;     }) }); </script> 

the cloning works clone div once.

$(document).ready(function() { var max_fields      = 10; //maximum input boxes allowed var wrapper         = $(".input_fields_wrap"); //fields wrapper var add_button      = $(".add_field_button"); //add button id  var x = 1; //initlal text box count add_button.click(function(e){ //on add input button click     e.preventdefault();     if(x < max_fields){ //max input box allowed         x++; //text box increment         var clone = $( ".ahli_keluarga:first").clone().append('<a href="#" class="remove_field">remove</a>');         wrapper.append(clone); //     } });  wrapper.on("click",".remove_field", function(e){ //user click on remove text     e.preventdefault(); $(this).parent('div').remove(); x--; }) 

});

in events no need provide selectors again

add_button.click wrapper.on("click" 

edit : moved cloning inside event clone new instance not same instance inserted in dom.

i created fiddle you: https://jsfiddle.net/hpyzzcj9/