views:

81

answers:

2

I am trying to repeat something inside a jquery function. I tried a for loop, but it seems it doesnt like the syntax. for instance i have the 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 that in the end i end up having 3 . Thanks

+2  A: 

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

Note how i prefixed id with the word 'myCell', to ensure XHTML compliancy. (thanks to @Peter Ajtai for pointing that out).

EDIT

I just noticed another problem - you're using the .html function to add the cells. But .html replaces the entire html of the matched element. So you'll only ever end up with the last cell. :)

You're probably looking for the .append function:

$('tr').append('<td id=myCell"' + i + '"></td>');
RPM1984
The for loop will work, but you should to pay attention to where you declare `i`. Additionally, those IDs are not valid. They cannot begin with numbers.
Peter Ajtai
@Peter Ajtai - good point (answer updated). Wasn't paying attention to the ID's he was assigning, just the nature of the for loop.
RPM1984
The problem with this solution (I tried it before but tested again upon your advice) is that in the end inside the <tr></tr> there would only be one <td></td>. This is because inside the loop, the last go-around calls for only one <td><td>.
El Fuser
Append does the trick. Thanks
El Fuser
+1  A: 

Heres an option using an anonymous function.

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

Michael MacDonald