Search code examples
jqueryformscloneable

Cloning a Form in jQuery and Increasing the Index


This seems relatively simple, I'm just stumped on jQuery syntax.

Basically I want to take this form :

<div class="me_signup">
  <input type="text" name="referral[0][name]" id="referral_0_name">
  <br>
  <input type="text" name="referral[0][email]" id="referral_0_email">
</div>

And duplicate it with a button and increase the variable number..

$(".add_another_button").click(function(){
    ...
};

Solution

  • Something like this?

    $(".add_another_button").click(function() {
        var $newdiv = $(".me_signup:last").clone(true);
        $newdiv.find('input').each(function() {
            var $this = $(this);
            $this.attr('id', $this.attr('id').replace(/_(\d+)_/, function($0, $1) {
                return '_' + (+$1 + 1) + '_';
            }));
            $this.attr('name', $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
                return '[' + (+$1 + 1) + ']';
            }));
            $this.val('');
        });
        $newdiv.insertAfter('.me_signup:last');
    });