For loop inside jquery function

I am trying to repeat something inside a jquery function. I tried the for loop, but it seems to me that this does not look like syntax. for example i have a variable

var number = 2; 

Now I have

 $('tr').html('<td id="'+number+'"></td>'); 

what I want to do is loop from 0 to number (0,1,2), so in the end I get 3. Thanks

+4
source share
2 answers

There is probably a better way, but this should work.

 var loops = [1,2,3]; $.each(loops, function(index, val) { $('tr').html('<td id="myCell' + index + '"></td>'); }); 

This should also work (regular JS):

 var i; for(i=0; i<3; i++) { $('tr').html('<td id="myCell' + i + '"></td>'); } 

Notice how I prefix the id with the word "myCell" to ensure XHTML compliance. (thanks @Peter Ajtai for pointing this out).

EDIT

I just noticed another problem: you are using the .html function to add cells. But .html replaces the entire html of the associated element. This way you will always end up with the last cell. :)

You are probably looking for the .append function:

 $('tr').append('<td id="myCell' + i + '"></td>'); 

EDIT 2 - moved the double quote before myCell, not after.

+7
source

Here is an option to use an anonymous function.

 $('TR').html( function(){ var content=''; for (var i=0; i<=2; i++ ){ content=content+'<td id="id_'+i+'"></td>'; } return content; } ) 
+3
source

All Articles