Raffy T Lawrence Raffy T Lawrence - 4 months ago 27
Javascript Question

Javascript PHP How to make a realtime count of table row when change

I have a table that when i type on input field it will show those like data that i searched realtime, i mean it filtered the data when i type in textbox.

i already did the filtered but i want to add some features that shows a text that count how many rows are filtered.

like this

enter image description here

this is my filtering code

function searchTable(inputVal)
{
var table = $('#tblData');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if(allCells.length)
{
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text()))
{
found = true;
return false;
}
});
if(found == true)$(row).show();else $(row).hide();
}
});
}

Answer

You can count all / hidden / shown childs using jQuery selectors at the end of your code.

You can use these selectors respectively; tr, tr:hidden, tr:visible

function searchTable(inputVal) {
    var table = $('#tblData');
    table.find('tr').each(function(index, row) {
        var allCells = $(row).find('td');
        if (allCells.length) {
            var found = false;
            allCells.each(function(index, td) {
                var regExp = new RegExp(inputVal, 'i');
                if (regExp.test($(td).text())) {
                    found = true;
                    return false;
                }
            });
            if (found == true) $(row).show();
            else $(row).hide();
        }
    });
    /* Use these values and print / append something to your HTML. */
    var allChilds = $('#tblData').find('tr').length;
    var shownChilds = $('#tblData').find('tr:visible').length;
    var hiddenChilds = $('#tblData').find('tr:hidden').length;
    /* Use these values and print / append something to your HTML. */
    var countTemplate = "Your template, Total:"+allChilds;
    $("#counts").html(countTemplate);

}