Live search through table rows

前端 未结 15 1813
失恋的感觉
失恋的感觉 2020-11-29 00:52

I want to do a live search through the table rows, using jQuery, the \"live\" word is the key, because I want to type the keywords in the text input, on the same site and I\

15条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 01:30

    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 = '' + textToHighlight + '';
        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


提交回复
热议问题