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
  • 108,152
  • 195
  • 629
  • 1,012

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,150
  • 5
  • 18
  • 32
0

For your first question:

$('table tr').length;
Ivar
  • 4,344
  • 6
  • 38
  • 53
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
  • 105,798
  • 26
  • 196
  • 262
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
  • 249,100
  • 51
  • 377
  • 410