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,438
  • 68
  • 55
  • 126
woninana
  • 3,171
  • 9
  • 39
  • 65

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
  • 160,666
  • 24
  • 190
  • 242
8

To get the tr count using pure js;

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

JS Fiddle Demo

Kaf
  • 32,033
  • 7
  • 53
  • 77
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
  • 197,815
  • 30
  • 248
  • 265
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
  • 719
  • 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
  • 223,102
  • 54
  • 301
  • 354
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