Pregunta

Esto parece relativamente simple, sólo estoy confundido sobre la sintaxis de jQuery.

Básicamente quiero tomar esta forma:

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

y duplicar con un botón y aumentar el número variable ..

$(".add_another_button").click(function(){
    ...
};
¿Fue útil?

Solución

este ?

$(".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');
});

Otros consejos

Se puede poner toda esa HTML en una variable, y el uso .Append () para agregar esto a un elemento DOM en particular. Y, en caso de que clonar esto, asegúrese de cambio "id" a "clase", porque id debe ser único en cada página. un poco más sobre .Append () en la documentación oficial

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top