Jonas
Jonas

Reputation: 129075

How to count dynamically added table rows with jQuery?

How can I count the table rows that is added dynamically with jQuery?

I have tried with $('#mytbody').children().length; but it doesn't work with rows that are added dynamically.

Here is my code, also runnable in JsFiddle

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.2.min.js">
<script>
$(function() {
    $('#add').bind('click', function() {
        $('#mytbody').after('<tr><td>'+ new Date() +'</td></tr>');
        var count = $('#mytbody').children().length;
        $('#counter').html(count);
    });
});
</script>
</head>
<body>
<button id="add">Add row</button>
<table>
    <tbody id="mytbody">
    </tbody>
</table>
Number of rows: <span id="counter"></span>
</body>
</html>

Upvotes: 3

Views: 29259

Answers (5)

sankar.suda
sankar.suda

Reputation: 1147

You are adding rows outside of tbody.

Change after to prepend

will work..

or change count to var count = $('table tr').length;

http://jsfiddle.net/H8sBr/442/

Upvotes: 3

Girish Kumar
Girish Kumar

Reputation: 450

It looks there is some bug (not sure) in jQuery; row length is not getting updated if you add table row dynamically.

var rowCount = $("#tableId > tbody > tr").length; 

will not return correct count if you add row dynamically.

Simple solution is to use:

var rowCount = document.getElementById("tableId").rows.length;

Yes, you can use jQuery with javascript.

Upvotes: 0

meo
meo

Reputation: 31259

http://jsfiddle.net/H8sBr/2/

you need to use .append() not .after(). After adds a element After your tbody but you count elements Inside your tbody. If you use append, you add them at the end of the tbody. Alternately you could use .prepend() to add entries on top of the table.

PS: This is a commun misconception because of the css selector .after() that adds content after the content of the selected element not after the element.

Upvotes: 4

NimChimpsky
NimChimpsky

Reputation: 47310

Just use a counter,it has less dom lookups :

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

Upvotes: 1

whostolemyhat
whostolemyhat

Reputation: 3123

Try altering count to

var count = $('table tr').length;

This seems to work - not sure why acting on the tbody doesn't.

Edit: jsFiddle

Upvotes: 3

Related Questions