clone div

by Shashi Kumar Nagulakonda

HTML

<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>

CSS

body {
  padding: 10px;
}

.clonedInput {
  padding: 10px;
  border-radius: 5px;
  background-color: #def;
  margin-bottom: 10px;
}

.clonedInput div {
  margin: 5px;
}

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();
  });

});