user8785970
user8785970

Reputation:

Having a for loop inside a jQuery append Method

My Question
I am having trouble finding how to place a for loop inside a jQuery append method. Should it be a strong, should it be just there, how do I format the code so it works?

My Code

window.onload = function () {
    $(function () {
        $('#li22').append($('<table/>').append(for (var i = 0; i <= 3; i++) {'$('#li22').append($(""));'}));
    });
}

Upvotes: 0

Views: 3121

Answers (3)

Younes Zaidi
Younes Zaidi

Reputation: 1190

Try Like this .

$(document).ready(function () {

       var string="<table>";
        for (var i = 0; i <= 3; i++) 
        { 
           string += "what you need";
        }
        string +="</table>"
        $('#li22').append(string);
    });

Upvotes: 0

Jesse Schokker
Jesse Schokker

Reputation: 896

You can not execute code inside of a function's argument. Therefor, the code must be formatted like:

window.onload = function () {

    $(function () {

        var tableTag = $('<table><table/>');

        $('#li22').append( tableTag );

        for (var i = 0; i <= 3; i++) {

            $( tableTag ).append( "" );

        }

    });

}

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly, don't put a for loop directly in the append() method. Secondly, don't put a document.ready event handler inside a window.onload handler - it's pointless.

Also, it's not exactly clear what you're trying to achieve. You're appending a table to #li22, then appending nothing to #li22 and returning that to the table...? As such the below is a general guide on how to use append() properly.

append() accepts a either string, so you should put the for outside the append(), like this:

$(function () {
  for (var i = 0; i <= 3; i++) {
    $('#li22').append($('<table/>'));
  }
});

Alternatively you can provide a function to append() which returns the HTML to be appended. You can put the for in there:

$(function () {
    $('#li22').append(function() {
      var html = '';
      for (var i = 0; i <= 3; i++) {
        html += '<table></table>';
      }
      return html;
    });
  }
});

Upvotes: 1

Related Questions