Live search through table rows

前端 未结 15 1861
失恋的感觉
失恋的感觉 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:22

    I used the previous answers and combine them to create:

    Search any columns by hide rows and highlighting

    Css for highlight found texts:

    em {
       background-color: yellow
    }
    

    Js:

    function removeHighlighting(highlightedElements) {
       highlightedElements.each(function() {
          var element = $(this);
          element.replaceWith(element.html());
       })
    }
    
    function addHighlighting(element, textToHighlight) {
       var text = element.text();
       var highlightedText = '' + textToHighlight + '';
       var newText = text.replace(textToHighlight, highlightedText);
    
       element.html(newText);
    }
    
    $("#search").keyup(function() {
       var value = this.value.toLowerCase().trim();
    
       removeHighlighting($("table tr em"));
    
       $("table tr").each(function(index) {
          if (!index) return;
          $(this).find("td").each(function() {
             var id = $(this).text().toLowerCase().trim();
             var matchedIndex = id.indexOf(value);
             if (matchedIndex === 0) {
                addHighlighting($(this), value);
             }
             var not_found = (matchedIndex == -1);
             $(this).closest('tr').toggle(!not_found);
             return not_found;
          });
       });
    });
    

    Demo here

提交回复
热议问题