Listening for changes in the number of rows in a table

I used an html table. My requirement: I want to listen for line count changes. Is there anyway to achieve this?

Note. I have no add / remove line functions to achieve.

Moreover, I have tried this,

$("#myTable>tbody>tr").watch("length", function () {
    alert("row count changed..")
});

      

But the above code doesn't work for me. Can any of you know how to do this?

Thanks in advance,

-Raja.

+3


source to share


4 answers


The only cross-browser way to do this at the moment would be with setInterval and possibly a custom event.

setInterval(function() {
    var $t = $("#myTable"),
        rowCount = $t.data("rowCount"),
        rowLength = $t.find("tbody").children().length;
    if (rowCount && rowCount !== rowLength) {
        $t.trigger("rowcountchanged").data("rowCount", rowLength);
    }
    else if (!rowCount) {
        $t.data("rowCount", rowLength);
    }

}, 50);​
$("#myTable").on("rowcountchanged",function(){
    alert($(this).data("rowCount"));
});

      

I suggest firing the event manually when the number of rows changes, rather than using an interval if possible.



UPDATE:
Use the jqGrid event refresh

.

var rowCount = $("#gridid>tbody>tr").length;
jQuery("#gridid").jqGrid({
...
   refresh: function(){ 
      var currCount = $("#gridid>tbody>tr").length;
      if (currCount !== rowCount) {
          alert("Number of rows changed!");
          rowCount = currCount;
      }
   },
...
});

      

If you manually delete any lines on click, you will also need to run your code if it does not reload the grid.

+3


source


You can monitor the DOM DOMSubtreeModified event (note that the event is deprecated, so if anyone has a suggestion for a better event to monitor, please change that) that fires when the DOM tree changes. We can use jQuery's bind function to trigger a function when an event is triggered on the table. This function can check if the number of lines has changed.

var numberOfRows = $("#myTable>tbody>tr").length;
$("#myTable").bind("DOMSubtreeModified", function() {
    if($("#myTable>tbody>tr").length !== numberOfRows){
        numberOfRows = $("#myTable>tbody>tr").length;
        alert("row count changed..");
    }
});

      



Try it!

See: Is there a JavaScript / jQuery DOM change listener?

+3


source


http://www.w3.org/TR/DOM-Level-2-Events/events.html - you can use this. But there is no implementation or polyfill in IE.

Also you can check TR counter with timer-triggered function.

0


source


I did it once with a timer. It's not very pretty, but it works in almost every browser I guess ...

http://jsfiddle.net/q5Eqr/

var html;
setInterval(function() {
    var table = $('table');
    if($('table').html() != html){
        alert('Changed!');
        html = $('table').html();
    }
}, 500);

      

0


source







All Articles