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.
source to share
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.
source to share
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..");
}
});
source to share
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.
source to share