Search Table Row by jquery

Search Table Row by jquery

Search content from table using jQuery. Live searching method via jquery

Create function to remove highlight content. If content not matched.

function removeHighLighting(elm){
        elm.each(function(){
            var element = $(this);
            element.replaceWith(element.html());
        })
    }

Create function to highlight matched content.

function addHighLighting(elm, data){
        var text = elm.text();
        var highlightedText = '<em>' + data+ '</em>';
        var newText = text.replace(data, highlightedText);
        elm.html(newText);
    }

Search text on keyup

$("#search").on("keyup", function() {
        var value = $(this).val();
        removeHighLighting($("table tr em"));
        $("table tr").each(function(index) {
            if (index !== 0) {
                $row = $(this);       
                var $tdElement = $row.find("td:first");
                var id = $tdElement.text();
                var matchedIndex = id.indexOf(value);               
                if (matchedIndex != 0) {
                    $row.hide();
                }
                else {
                   addHighLighting($tdElement, value);
                    $row.show();
                }
            }
        });
    });

Method 2:

$("#search").keyup(function(){
        _this = this;
        // Show only matching TR, hide rest of them
        $.each($("#table tbody tr"), function() {
            if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) === -1)
               $(this).hide();
            else
               $(this).show();                
        });
    });

Comments