As the title says, what I am trying to do is to have jQuery add a number of extra fieldsets based on the value selected in a drop-down box. For example, when the page loads,
Why are you cloning instead of just doing something like this (together with your current event listener)?
$(".divWhereTheseGo").empty();
var count = 0;
while (count < maxItems) {
$(".divWhereTheseGo").append("<fieldset id=\"" + count + "\">your form info</fieldset>");
count++;
}
The count in the fieldset is how you can handle the unique id issue.
I don't like the solution of Nate B.
This does what you want and similar to what you did. Keeps only the ids in a data attribute on the original element (instead of keeping the whole clone object which could use massive amounts of memory). Keeps all values already entered. Doesn't recreate everything if you change from e.g. 3 to 5. Instead only generates two new fieldsets. Removes them in reverse order they where created.
jQuery.fn.fieldsManage = function (number) {
var ele = $(this);
var clones = ele.data("clones");
clones = clones ? clones : new Array(ele.attr("id"));
if (clones.length < number) {
var clone;
while(clones.length < number) {
clone = ele.clone(true);
var id = clones[0]+clones.length;
clone.attr("id", id);
$("#"+clones[clones.length-1]).after(clone);
clones.push(id);
}
} else {
while(clones.length > number) {
$("#"+clones.pop()).remove();
}
}
ele.data("clones", clones);
}
$(document).ready(function() {
$("#itemCount").change(function() {
$("#item_dup_1").fieldsManage(this.value);
});
});