Pergunta

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(){
    ...
};
Foi útil?

Solução

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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top