Reputation: 353
I have a text file with values, which I read and display on my page. I'm trying to figure out whether there is a way to create a jQuery loops to process this information, so there isn't that many repetitions:
$('#number1').text(table[0][2]);
$('#number2').text(table[1][2]);
$('#number3').text(table[2][2]);
$('#number4').text(table[3][2]);
$('#number5').text(table[4][2]);
$('#number6').text(table[5][2]);
Thank you in advance!
Upvotes: 0
Views: 51
Reputation:
$.each( table, function ( index ) {
$( "#number" + ( index + 1 ) ).text( table[ index ][ 2 ] );
});
Upvotes: 1
Reputation: 2435
Expanding on the loop/iteration basics and the logic in your code, i think the easiest way to do it is:
for(var i = 0; i < table.length; i++) {
$('#number' + (i+1)).text(table[i][2]);
}
Upvotes: 2
Reputation: 171679
Assuming the element order in page is same as order of array you can use text(function)
which loops over all the elements in collection and exposes their index within the collection.
$('#number1,#number2,#number3....').text(function(i){
return table[i][2];
});
If all these elements had a common class it would simplify the initial selector
Upvotes: 2