Amit
Amit

Reputation: 26316

how to fill a table with array elements in jquery?

i have a table in html like this:

<table id="someTable">
   <tr>
       <td>
           <span></span>
       </td>
   </tr>
   <tr>
       <td>
           <span></span>
       </td>
   </tr>
   <tr>
       <td>
           <span></span>
       </td>
   </tr>
</table>

i have an array someArray with three values in it. I want to iterate through the array and set each array items to a span on each row.

i tried a jquery code like this

$('#someTable tr').each(function(i) {
      $(this + 'td:first span').html(someArray[i]);
});

the problem is it is setting the last value on the array to all the span's how to fix it?

Upvotes: 4

Views: 3069

Answers (2)

Sarfraz
Sarfraz

Reputation: 382881

You can use find():

$('#someTable tr').each(function(i) {
  $(this).find('td:first span').html(someArray[i]);
});

Or context selector:

$('#someTable tr').each(function(i) {
  $('td:first span', $(this)).html(someArray[i]);
});

Upvotes: 2

karim79
karim79

Reputation: 342765

Use .find(). Appending a selector to this will not work:

$('#someTable tr').each(function(i) {
      $(this).find('td:first span').html(someArray[i]);
});

Upvotes: 3

Related Questions