1

I just want to count the number of rows,

   <button id="add">Add row</button>
<table>
    <tbody id="mytbody">
    </tbody>
</table>
Number of rows: <span id="counter"></span>

Javascript:

$(function() {
    $('#add').bind('click', function() {
        $('#mytbody').after('<tr><td>'+ new Date() +'</td></tr>');
        var count = $('#mytbody').children().length;
        $('#counter').html(count);
    });
});

I found this jQuery: count number of rows in a table

and this doesn't works http://jsfiddle.net/H8sBr/

I just don't get it working. help?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
woninana
  • 3,409
  • 9
  • 42
  • 66

7 Answers7

12

The script is wrong, use append():

$(function() {
    $('#add').bind('click', function() {
        $('#mytbody').append('<tr><td>'+ new Date() +'</td></tr>');
        var count = $('#mytbody').children('tr').length;
        $('#counter').html(count);
    });
});

Demo: http://jsfiddle.net/praveenscience/H8sBr/115/

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
8

To get the tr count using pure js;

var count = document.getElementById("mytbody").getElementsByTagName("tr").length;

JS Fiddle Demo

Kaf
  • 33,101
  • 7
  • 58
  • 78
1

Try this jsFiddle example.

$('#add').bind('click', function () {
    $('#mytbody').append('<tr><td>' + new Date() + '</td></tr>');
    var count = $('#mytbody tr').length;
    $('#counter').html(count);
});

You can use simply $('#mytbody tr').length but you must also use append instead of after.

j08691
  • 204,283
  • 31
  • 260
  • 272
1

since you are using after(), your code is adding the tr after the #mytbody,

<button id="add">Add row</button>
<table>
    <tbody id="mytbody">
    </tbody>
    <tr>Tue Feb 26 2013 23:41:09 GMT+0530 (India Standard Time)</tr>
    <tr>Tue Feb 26 2013 23:41:09 GMT+0530 (India Standard Time)</tr>   
</table>

so when you executing your code

$('#mytbody').children().length;

it always return you 0.

so instead of after() try to use append() http://forum.jquery.com/topic/after-vs-append

http://jsfiddle.net/H8sBr/118/

Aman Agarwal
  • 727
  • 6
  • 15
0

You don't .append() new <tr> nodes, you're inserting them after the table body. Use

$('#mytbody').append('<tr><td>'+ new Date() +'</td></tr>');

instead.

jAndy
  • 231,737
  • 57
  • 305
  • 359
0

Try this:

    $('#add').click(function() {
        $('#mytbody').append('<tr><td>'+ new Date() +'</td></tr>');
        var count = $('#mytbody > TR').length;
        $('#counter').html(count);
    });
Silent Byte
  • 190
  • 1
  • 11
0

Rectified your JS code. http://jsfiddle.net/HwEA7/

$(function() {
    $('#add').bind('click', function() {
        $('#mytbody').append('<tr><td>'+ new Date() +'</td></tr>');
        var count = $('#mytbody tr').length;
        $('#counter').html(count);
    });
});
  1. Use append to add row after <tbody>
  2. Count number of row as $('#mytbody tr').length
Anup Khandelwal
  • 365
  • 2
  • 6
  • 23