Live search through table rows

I’m not sure how efficient this is but this works:

$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index != 0) {

            $row = $(this);

            var id = $row.find("td:first").text();

            if (id.indexOf(value) != 0) {
                $(this).hide();
            }
            else {
                $(this).show();
            }
        }
    });
});​

DEMO – Live search on table


I did add some simplistic highlighting logic which you or future users might find handy.

One of the ways to add some basic highlighting is to wrap em tags around the matched text and using CSS apply a yellow background to the matched text i.e: (em{ background-color: yellow }), similar to this:

// removes highlighting by replacing each em tag within the specified elements with it's content
function removeHighlighting(highlightedElements){
    highlightedElements.each(function(){
        var element = $(this);
        element.replaceWith(element.html());
    })
}

// add highlighting by wrapping the matched text into an em tag, replacing the current elements, html value with it
function addHighlighting(element, textToHighlight){
    var text = element.text();
    var highlightedText="<em>" + textToHighlight + '</em>';
    var newText = text.replace(textToHighlight, highlightedText);
    
    element.html(newText);
}

$("#search").on("keyup", function() {
    var value = $(this).val();
    
    // remove all highlighted text passing all em tags
    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 {
                //highlight matching text, passing element and matched text
                addHighlighting($tdElement, value);
                $row.show();
            }
        }
    });
});

Demo – applying some simple highlighting


Leave a Comment