1

w jQuery - is it possible to setup a listener that can count the number of rows in a table.

And when the row count changes do X if the count is eq 0 or Y is > 0?

Thanks

AnApprentice
  • 103,298
  • 185
  • 610
  • 989

4 Answers4

1

One way is to use time listener :

 var time = setInterval(function(){   
                                   alert( $('#table tr').length ); 
                                  },1000 ); 

Or you can put it when the event associated with change num rows executed .

shox
  • 1,130
  • 4
  • 18
  • 32
0

For your first question:

$('table tr').length;
Ivar
  • 4,244
  • 6
  • 36
  • 52
0

Both .length and .size() will give you the same information. If the table ID is tbl1, then you use the jQuery CSS selector

$('#tbl1 tr')

If you are using <thead>, <tbody>, <tfoot> properly, then you should use the below to count only the body rows, otherwise take 1 or 2 off the .length result from the above.

$('#tbl1 tbody tr')

As for observing the row count changes, you need either

  1. a global var that stores the current row count, coupled with a setInterval event (say 100ms) that checks for changes and raises an event; or
  2. a class that encapsulates this behaviour with an internal var, but also using setInterval
RichardTheKiwi
  • 102,799
  • 24
  • 193
  • 261
0

You could use something like:

$('#tableID').bind('DOMNodeInserted', function() {
    var count = $('table tr').length;
    alert("The number of rows has changed, there are now " + count + " rows.");
    });

JS Fiddle demo.

David Thomas
  • 240,457
  • 50
  • 366
  • 401