1

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(){
    ...
};
Trip
  • 26,756
  • 46
  • 158
  • 277

2 Answers2

9

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');
});
gnarf
  • 105,192
  • 25
  • 127
  • 161
  • YOU ARE GENIUS STATUS. Where is the golden version of you so that I can make proper obeisances? – Trip Nov 02 '10 at 15:48
  • i know i already checked this off, but i'm still blown away. I can't thank you enough. Your understanding of regex is amazingly on point. – Trip Nov 02 '10 at 15:55
0

You can put all that html in a variable, and use .append() method to add this to a particular DOM element. And, should you clone this, be sure to change "id" to "class", because id must be unique on each page. Some more about .append() in official documentation

Arnthor
  • 2,563
  • 6
  • 34
  • 54