Chauhan
Chauhan

Reputation: 2581

How to clone in jquery

I am using this code for cloning.

  1. I want to modify this code when I click on the clone button it's cloning again and again clone and remove button for every new generated dynamic div.

  2. When I click on the clone button the first time, it clone the same div using same id id =clonedInput1, after that it start increment.

You can find a working version here http://jsfiddle.net/shalucosmic/FEpMk/7/

  <script type="text/javascript">
  $(document).ready(function(){
        //jQuery(this).parent(".clonedInput")
           var regex = /^(.*)(\d)+$/i;
           var cloneIndex = $(".clonedInput").length;

           $("button.clone").live("click", function(){

           $(this).parents(".clonedInput").clone().appendTo("body").attr("id",  "clonedInput" +  cloneIndex)
           .find("*").each(function() {
            var id = this.id || "";
            var name = this.name || "";

            var match = id.match(regex) || [];

           var matchname = name.match(regex) || [];
           if (match.length == 3) {
            this.id = match[1] + (cloneIndex);
           }
          if (matchname.length == 3) {
            this.name = match[1] + (cloneIndex);
          }
 });
cloneIndex++;

});
$("button.remove").live("click", function(){
   $(this).parents(".clonedInput").remove();
});

});

  <div id="clonedInput1" class="clonedInput">
   <input type="text" name="contributer1" value="" id="contributer1"/>

   <div class="actions">
    <button class="clone">Clone</button> 
    <button class="remove">Remove</button>
   </div>
 </div>

Upvotes: 0

Views: 192

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

You can simplify it as

$(document).ready(function() {
    // jQuery(this).parent(".clonedInput")
    var regex = /^(.*)(\d)+$/i;
    var cloneIndex = $(".clonedInput").length + 1;

    $(document).on("click", 'button.clone', function() {
        $(this).closest(".clonedInput").clone().appendTo("body").attr("id",
                "clonedInput" + cloneIndex).find("[id], [name]").each(
                function() {
                    this.id = this.id.replace(/\d+$/, cloneIndex);
                    this.name = this.name.replace(/\d+$/, cloneIndex);
                });
        cloneIndex++;
    });

    $("button.remove").live("click", function() {
                $(this).parents(".clonedInput").remove();
            });

});

demo: Fiddle

Upvotes: 2

jaychapani
jaychapani

Reputation: 1509

While declaring cloneIndex you need to declare it as below.

var cloneIndex = $(".clonedInput").length+1;

DEMO

Upvotes: 1

bipen
bipen

Reputation: 36531

you need to add 1 in cloned input length

var cloneIndex = $(".clonedInput").length + 1;
                                    // -----^^^^ here

fiddle here

Upvotes: 1

Related Questions