Question

I'm trying to use jQuery to append a cloned div at the end of a form. Here's how it works:

 var student_number = 1;
    var orig_student = $("#student-1").clone();

    $("#add-student-link").click(function() {
         ++student_number;
         orig_student.appendTo('form.reg').attr('id', 'student-' + (student_number)).addClass("additional-student");
    });

And this works great the first time, I get a div that looks like this:

<div id="student-2" class="additional-student"></div>

But after that, the div gets replaced with another div with the id "student-3". student-3 should have been a new div, not replaced student-2. Any ideas?

Was it helpful?

Solution

You're just moving the clone instead of duplicating (see the comments left below your question).

$("#add-student-link").click(function() {
     ++student_number;
     $("#student-1").clone().attr('id', 'student-' + (student_number)).addClass("additional-student").appendTo('form.reg');
});

If you're cloning to keep a copy that's clean (could be input fields in the element for all I know) then clone the clone.

var orig_student = $("#student-1").clone().attr('id','');
$("#add-student-link").click(function() {
     ++student_number;
     orig_student.clone().attr('id', 'student-' + (student_number)).addClass("additional-student").appendTo('form.reg');
});

OTHER TIPS

When you click the first time, it works because it uses the cloned div.

By clicking for the second time, then the variable orig_student still references the same div and you are appending it again and changing the class.

To make it work you need to create another clone to append inside the function. Because that is what is going to be executed on click.

var student_number = 1;
var orig_student = $("#student-1"); // No need to clone it here

$("#add-student-link").click(function() {
     ++student_number;
     // Create a new clone of your original div and append it
     // Like this we clone it only when really needed
     orig_student.clone().appendTo('form.reg').attr('id', 'student-' + (student_number)).addClass("additional-student");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top