$("#mySelect").change(function() {
var myVar = $('#MyDiv');
for (var i=0;i<this.value;i++)
{
myVar.clone().appendTo('#formContainer');
}
});
Any improvements to readability or performance welcome
I agree with @Diodeus, you should go with creating html string and then append it in one go. Try this.
$("#mySelect").change(function() {
var myVar = $('#MyDiv'),
html = [],
count = parseInt(this.value, 10),
myDivHTML = $('#MyDiv').wrap('<div />').parent().html();
for (var i = 0; i < count; i++){
myVar.push(myDivHTML);
}
$('#formContainer').append(html.join(''));
});
Here you are (that's how I would do):
$("#mySelect").live('change', function() {
var html = $('<div />').append($('#my-div').clone());
for (var i = 0; i < this.value; i++) {
html.append(html.clone());
}
});
If I got right, your trying to nest clone in div on each iteration... that seems strange to me... Also use live('change', ...); to bind triggers, in this case your code would work not just for loaded at the beginning HTML, but for loaded via AJAX too.
{and}characters in my code on their own lines; it just makes it that much more readable to me.