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