2

I have a problem where the :eq() does not accept the counter, n, to insert values to a new column to the table in the HTML.

$(document).ready(function() {  
    var $tablerow = $('table.table').find('tr');
    count = 0;

    $tablerow.each(function(index, value){
        count += 1;
        var $listitem = $(this);
        n = parseInt($listitem.index());
        var $newRow = $("<td>" + n + "</td>");
        $("table.table tr:eq(n)").append($newRow);
    });
});  

HTML

<table class="table">
    <tr><td>First row</td></tr>
    <tr><td>second row</td></tr>
    <tr><td>third row</td></tr>
    <tr><td>fourth row</td></tr>
    <tr><td>fifth row</td></tr>
    <tr><td>sixth row</td></tr>
    <tr><td>seventh row</td></tr>
    <tr><td>eighth row</td></tr>
</table>
Community
  • 1
  • 1
Isoubb
  • 23
  • 1
  • 3
  • You don't need find. You just want an array of the TR's. `$('.table tr')` will grab those. But if you have more than one table with that class, beware (same goes for find mind you). ;-) – Greg Pettit Mar 09 '12 at 05:45
  • 1
    what do you want? Question is not clear. – Sara Mar 09 '12 at 05:46

4 Answers4

1

Written as-is, you're doing nothing more than writing a literal character, 'n', into .eq() method. Try this:

$("table.table tr:eq(" + n + ")").append($newRow);
Tieson T.
  • 20,774
  • 6
  • 77
  • 92
0

May be try using it like previous line where you used qoutes $("table.table tr:eq(" + n + ")").append($newRow);

supriya
  • 108
  • 6
0

No need to index this inside $.each since as your arguments show the first one is index.

 $(document).ready(function() {  
    var $tablerow = $('table.table tr');

    $tablerow.each(function(index,element){
       /* "this" is current row*/
         $(this).append("<td>" + index+1 + "</td>" )
    });
});  
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Replace

 var $newRow = $("<td>" + n + "</td>");
 $("table.table tr:eq(n)").append($newRow);`

with

var $newRow = $("<td>" + (n+1) + "</td>");
$("table.table tr:eq(" + n + ")").append($newRow);

This will work

Sara
  • 14,098
  • 13
  • 34
  • 50