0
$("#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

7
  • 1
    This kind of question could be posted on codereview.stackexchange.com Commented Feb 6, 2012 at 15:30
  • 1
    isn't it bad practice to put { on it's own line in javascript? Commented Feb 6, 2012 at 15:31
  • It is, read: javascript.crockford.com/style1.html Commented Feb 6, 2012 at 15:38
  • Ugh. Style is a personal thing - it's more important that everyone looking at the file does it the same way than to do it "right". Commented Feb 6, 2012 at 15:40
  • @ianbarker That's not something I've ever heard before, and really doesn't make any sense to me. I almost always put the { and } characters in my code on their own lines; it just makes it that much more readable to me. Commented Feb 6, 2012 at 15:50

3 Answers 3

4

DOM re-writes are the most expensive. Build your HTML up in memory (or as a string) and insert it in one go AFTER the loop.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.