【问题标题】:Live search through table rows实时搜索表格行
【发布时间】:2012-09-08 03:17:38
【问题描述】:

我想通过表格行进行实时搜索,使用 jQuery,“实时”词是关键,因为我想在同一站点上的文本输入中键入关键字,我希望 jQuery自动排序(或删除那些与搜索查询不匹配的)表行。

这是我的 HTML:

<table>
    <tr><th>Unique ID</th><th>Random ID</th></tr>
    <tr><td>214215</td><td>442</td></tr>
    <tr><td>1252512</td><td>556</td></tr>
    <tr><td>2114</td><td>4666</td></tr>
    <tr><td>3245466</td><td>334</td></tr>
    <tr><td>24111</td><td>54364</td></tr>
</table>

如果我愿意的话。通过Unique ID 搜索,它应该只显示唯一ID 从特定数字开始的行。铁。如果我在搜索输入框中输入“2”,则应保留以下行,因为它们以 2 开头:

<table>
    <tr><th>Unique ID</th><th>Random ID</th></tr>
    <tr><td>214215</td><td>442</td></tr>
    <tr><td>2114</td><td>4666</td></tr>
    <tr><td>24111</td><td>54364</td></tr>
</table>

如果我输入24,那么应该只有一行可见,因为它从24开始:

<table>
    <tr><th>Unique ID</th><th>Random ID</th></tr>
    <tr><td>24111</td><td>54364</td></tr>
</table>

如果你们能给我一些关于如何做这样的事情的提示,我将非常感激。

谢谢。

【问题讨论】:

标签: jquery search live tablerow


【解决方案1】:

我不确定它的效率如何,但这很有效:

$("#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 - 实时搜索表


我确实添加了一些简单的突出显示逻辑,您或未来的用户可能会觉得方便。

添加一些基本突出显示的方法之一是将em标签包裹在匹配的文本周围,并使用CSS为匹配的文本应用黄色背景,即:(em{ background-color: yellow }),类似于:

// 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 - 应用一些简单的高亮显示


【讨论】:

  • 顺便说一句。你能告诉我,如果可以为Random ID 搜索做同样的事情吗? :first 选择器在这种情况下不起作用。
  • 你的意思是如果输入值匹配任一列?
  • 没关系,我只是为每一列设置了唯一的类,现在可以了。您对如何突出显示输入的文本有任何想法吗?
  • 我不知道我的头顶,但经过一番谷歌搜索后,我发现了这个:johannburkard.de/blog/programming/javascript/…,在这篇文章中也提到了这个:stackoverflow.com/questions/119441/highlight-a-word-with-jquery
  • 非常感谢,这是很棒的代码。对我来说工作正常,除了“索引!== 0”让我的第一个 tr 行一直出现,无论搜索结果是什么(我想原因是我也有 tbody),我通过将其更改为“索引!== -1"。也许已经很晚了,但是将您突出显示的文本更改为“var highlightText = '' + textToHighlight + '';”将添加背景黄色,如果它不适合你。
【解决方案2】:

这是一个搜索两列的版本。

$("#search").keyup(function () {
    var value = this.value.toLowerCase().trim();

    $("table tr").each(function (index) {
        if (!index) return;
        $(this).find("td").each(function () {
            var id = $(this).text().toLowerCase().trim();
            var not_found = (id.indexOf(value) == -1);
            $(this).closest('tr').toggle(!not_found);
            return not_found;
        });
    });
});

演示:http://jsfiddle.net/rFGWZ/369/

【讨论】:

  • 这很好用!我将它用作具有 4-8 列的大尺寸表格的实时搜索功能 - 谢谢!对于那些只需要在他们的表中搜索特定列的人,您可以添加到.find("td") 并使其类似于.find("td.searchable")
  • 我认为这更有用,因为您不仅查看一列,而且查看整行:)
  • 在这个答案中,我们可以搜索表中的任何列。我需要这个。谢谢
【解决方案3】:

François Wahl approach,但短一点:

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

    $("table").find("tr").each(function(index) {
        if (!index) return;
        var id = $(this).find("td").first().text();
        $(this).toggle(id.indexOf(value) !== -1);
    });
});

http://jsfiddle.net/ARTsinn/CgFd9/

【讨论】:

  • @François Wahl:耶!忘记了:first。现已添加!
  • 使用三元运算符? ... : 来执行函数并不是它的本意。该运算符适用于每个表达式都是没有副作用的简单语句的赋值。调用函数是一个副作用。打开您的小提琴并单击JSLint 按钮以验证您的代码,您还将看到Problem at line 7 character 69: Expected an assignment or function call and instead saw an expression. 有关更多详细信息,请参阅文档msdn.microsoft.com/en-us/library/be21c7hw(v=vs.94).aspx 例如,C# 等语言不会让您编译它。
  • @FrançoisWahl:哇,我不知道,谢谢...真的很有帮助!但是,顺便说一下,“副作用”是什么?我认为每个浏览器都了解条件运算符(?),还是不了解?
  • 副作用是任何改变状态的东西。当您使用三元运算符分配值时,您分配的值应该是简单的语句。如果您进行方法调用,问题在于您不知道该方法的作用或它可能调用的其他方法。比如说你打电话给$(this).hide。该方法调用具有副作用,因为它更改了指定元素的状态,这不是您在使用赋值调用时想要发生的事情。这篇文章解释得很好:programmers.stackexchange.com/questions/40297/…
  • 感谢使用 jQuery 的函数而不是 CSS 选择器来不使用 Sizzle。这个版本在小规模上也更快。 (保罗爱尔兰)
【解决方案4】:

这是它的纯 Javascript 版本,带有 LIVE search for ALL COLUMNS

function search_table(){
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("search_field_input");
  filter = input.value.toUpperCase();
  table = document.getElementById("table_id");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td") ; 
    for(j=0 ; j<td.length ; j++)
    {
      let tdata = td[j] ;
      if (tdata) {
        if (tdata.innerHTML.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";
          break ; 
        } else {
          tr[i].style.display = "none";
        }
      } 
    }
  }
}

【讨论】:

    【解决方案5】:

    我接受了 yckart 的回答:

    • 为了便于阅读,将其隔开
    • 不区分大小写的搜索
    • 比较中存在一个错误,已通过添加 .trim() 修复

    (如果您将脚本放在页面底部的 jQuery 包含下方,则不需要准备好文档)

    jQuery:

     <script>
        $(".card-table-search").keyup(function() {
            var value = this.value.toLowerCase().trim();
    
            $(".card-table").find("tr").each(function(index) {
                var id = $(this).find("td").first().text().toLowerCase().trim();
                $(this).toggle(id.indexOf(value) !== -1);
            });
        });
     </script>
    

    如果你想扩展它,让它遍历每个 'td' 并进行比较。

    【讨论】:

      【解决方案6】:

      老问题,但我知道如何更快地做到这一点。对于我的示例:我的表中有大约 10k 数据,所以我需要一些快速搜索机器。

      这是我所做的:

      $('input[name="search"]').on('keyup', function() {
      
              var input, filter, tr, td, i;
      
              input  = $(this);
              filter = input.val().toUpperCase();
              tr     = $("table tr");
      
              for (i = 0; i < tr.length; i++) {
                  td = tr[i].getElementsByTagName("td")[0]; // <-- change number if you want other column to search
                  if (td) {
                      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                          tr[i].style.display = "";
                      } else {
                          tr[i].style.display = "none";
                      }
                  }
              }
          })
      

      希望对某人有所帮助。

      【讨论】:

        【解决方案7】:

        您可以使用下面的 JS 函数来根据某些指定的列过滤行,请参见 searchColumn 数组。它取自 w3 学校,稍加定制以在给定的列列表上搜索和过滤。

        HTML 结构

        <input style="float: right" type="text" id="myInput" onkeyup="myFunction()" placeholder="Search" title="Type in a name">
        
             <table id ="myTable">
               <thead class="head">
                <tr>
                <th>COL 1</th>
                <th>CoL 2</th>
                <th>COL 3</th>
                <th>COL 4</th>
                <th>COL 5</th>
                <th>COL 6</th>      
                </tr>
            </thead>    
          <tbody>
        
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
             </tr>
        
            </tbody>
        </tbody>
        

          function myFunction() {
            var input, filter, table, tr, td, i;
            input = document.getElementById("myInput");
            filter = input.value.toUpperCase();
            table = document.getElementById("myTable");
            tr = table.getElementsByTagName("tr");
        
             var searchColumn=[0,1,3,4]
        
            for (i = 0; i < tr.length; i++) {
        
              if($(tr[i]).parent().attr('class')=='head')
                {
                    continue;
                 }
        
            var found = false;
              for(var k=0;k<searchColumn.length;k++){
        
                td = tr[i].getElementsByTagName("td")[searchColumn[k]];
        
                if (td) {
                  if (td.innerHTML.toUpperCase().indexOf(filter) > -1 ) {
                    found=true;    
                  } 
                }
            }
            if(found==true)  {
                tr[i].style.display = "";
            } 
            else{
                tr[i].style.display = "none";
            }
        }
        }
        

        【讨论】:

          【解决方案8】:

          这个对我来说是最好的

          https://www.w3schools.com/jquery/jquery_filters.asp

          <script>
          $(document).ready(function(){
            $("#myInput").on("keyup", function() {
              var value = $(this).val().toLowerCase();
              $("#myTable tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
              });
            });
          });
          </script>
          

          【讨论】:

            【解决方案9】:

            这是您可以使用 Ajax、PHP 和 JQuery 执行的操作。希望这有助于或给你一个开始。检查 php.ini 中的 mysql 查询。它匹配从 first 开始的模式。

            在此处查看现场演示和源代码。

            http://purpledesign.in/blog/to-create-a-live-search-like-google/

            创建一个搜索框,可以是这样的输入框。

            <input type="text" id="search" autocomplete="off">
            

            现在我们需要聆听用户在文本区域输入的任何内容。为此,我们将使用 jquery live() 和 keyup 事件。在每个 keyup 上,我们都有一个 jquery 函数“search”,它将运行一个 php 脚本。

            假设我们有这样的 html。我们有一个输入字段和一个列表来显示结果。

             <div class="icon"></div>
             <input type="text" id="search" autocomplete="off">
             <ul id="results"></ul>
            

            我们有一个 Jquery 脚本,它将监听输入字段上的 keyup 事件,如果它不为空,它将调用 search() 函数。 search() 函数将运行 php 脚本并使用 AJAX 在同一页面上显示结果。

            这里是 JQuery。

            $(document).ready(function() {  
            
                // Icon Click Focus
                $('div.icon').click(function(){
                    $('input#search').focus();
                });
            
                //Listen for the event
                $("input#search").live("keyup", function(e) {
                // Set Timeout
                clearTimeout($.data(this, 'timer'));
            
                // Set Search String
                var search_string = $(this).val();
            
                // Do Search
                if (search_string == '') {
                    $("ul#results").fadeOut();
                    $('h4#results-text').fadeOut();
                }else{
                    $("ul#results").fadeIn();
                    $('h4#results-text').fadeIn();
                    $(this).data('timer', setTimeout(search, 100));
                };
            });
            
            
            // Live Search
            // On Search Submit and Get Results
            function search() {
                var query_value = $('input#search').val();
                $('b#search-string').html(query_value);
                if(query_value !== ''){
                    $.ajax({
                        type: "POST",
                        url: "search_st.php",
                        data: { query: query_value },
                        cache: false,
                        success: function(html){
                            $("ul#results").html(html);
            
                        }
                    });
                }return false;    
            }
            

            }); 在 php 中,对 mysql 数据库进行查询。 php 将返回将使用 AJAX 放入 html 的结果。这里将结果放入一个 html 列表中。

            假设有一个虚拟数据库,其中包含两个表动物和鸟,其中两个相似的列名“type”和“desc”。

            //search.php
            // Credentials
            $dbhost = "localhost";
            $dbname = "live";
            $dbuser = "root";
            $dbpass = "";
            
            //  Connection
            global $tutorial_db;
            
            $tutorial_db = new mysqli();
            $tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
            $tutorial_db->set_charset("utf8");
            
            //  Check Connection
            if ($tutorial_db->connect_errno) {
                printf("Connect failed: %s\n", $tutorial_db->connect_error);
                exit();
            
            $html = '';
            $html .= '<li class="result">';
            $html .= '<a target="_blank" href="urlString">';
            $html .= '<h3>nameString</h3>';
            $html .= '<h4>functionString</h4>';
            $html .= '</a>';
            $html .= '</li>';
            
            $search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
            $search_string = $tutorial_db->real_escape_string($search_string);
            
            // Check Length More Than One Character
            if (strlen($search_string) >= 1 && $search_string !== ' ') {
                // Build Query
                $query = "SELECT *
                    FROM animals
                    WHERE type REGEXP '^".$search_string."'
                    UNION ALL SELECT *
                    FROM birf
                    WHERE type REGEXP '^".$search_string."'"
                    ;
            
            $result = $tutorial_db->query($query);
                while($results = $result->fetch_array()) {
                    $result_array[] = $results;
                }
            
                // Check If We Have Results
                if (isset($result_array)) {
                    foreach ($result_array as $result) {
            
                        // Format Output Strings And Hightlight Matches
                        $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
                        $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
                    $display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
            
                        // Insert Name
                        $output = str_replace('nameString', $display_name, $html);
            
                        // Insert Description
                        $output = str_replace('functionString', $display_function, $output);
            
                        // Insert URL
                        $output = str_replace('urlString', $display_url, $output);
            
            
            
                        // Output
                        echo($output);
                    }
                }else{
            
                    // Format No Results Output
                    $output = str_replace('urlString', 'javascript:void(0);', $html);
                    $output = str_replace('nameString', '<b>No Results Found.</b>', $output);
                    $output = str_replace('functionString', 'Sorry :(', $output);
            
                    // Output
                    echo($output);
                }
            }
            

            【讨论】:

              【解决方案10】:

              使用 yckart's answer,我可以搜索整个表 - 所有 td。

              $("#search").keyup(function() {
                  var value = this.value;
              
                  $("table").find("tr").each(function(index) {
                      if (index === 0) return;
              
                      var if_td_has = false; //boolean value to track if td had the entered key
                      $(this).find('td').each(function () {
                          if_td_has = if_td_has || $(this).text().indexOf(value) !== -1; //Check if td's text matches key and then use OR to check it for all td's
                      });
              
                      $(this).toggle(if_td_has);
              
                  });
              });
              

              【讨论】:

              • 嗨,这对我有用.. 但是如果我想让它不区分大小写怎么办?这意味着如果我输入“M”或“m”..无论大小写,它都会搜索所有“m”。谢谢!
              • 你是明星 :)
              • 很高兴,它帮助了@SohairAhmad :)
              【解决方案11】:

              如果一行中的任何单元格包含搜索的短语或单词,此函数会显示该行,否则将其隐藏。

                  <input type="text" class="search-table"/>  
                   $(document).on("keyup",".search-table", function () {
                              var value = $(this).val();
                              $("table tr").each(function (index) {
                                  $row = $(this);
                                  $row.show();
                                  if (index !== 0 && value) {
                                      var found = false;
                                      $row.find("td").each(function () {
                                          var cell = $(this).text();
                                          if (cell.indexOf(value.toLowerCase()) >= 0) {
                                              found = true;
                                              return;
                                          } 
                                      });
                                      if (found === true) {
                                          $row.show();
                                      }
                                      else {
                                          $row.hide();
                                      }
                                  }
                        });
                 });
              

              【讨论】:

                【解决方案12】:

                我使用了之前的答案并将它们组合起来创建:

                通过隐藏行和突出显示搜索任何列

                用于突出显示找到的文本的 Css:

                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 = '<em>' + textToHighlight + '</em>';
                   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;
                      });
                   });
                });
                

                演示here

                【讨论】:

                  【解决方案13】:
                  <!--code for table search start--> 
                  <script>
                      $(document).ready(function () {
                          $("#myInput").on("keyup", function () {
                              var value = $(this).val().toLowerCase();
                              $("#myTable tr").filter(function () {
                                  $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                              });
                          });
                      });
                  </script><!--code for table search end-->
                  

                  【讨论】:

                  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
                  【解决方案14】:
                  $("#search").on("keyup", function() {
                          var value = $(this).val().toLowerCase();
                          $("tbody tr").filter(function() {
                              $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                          });
                      });
                  

                  假设有一个带有 tbody 的表。您也可以使用 find 进行搜索,或者如果表格有 ID,您可以使用 id

                  【讨论】:

                    【解决方案15】:

                    大家好,2020 年还在寻找。我从这里得到了一些答案,并制作了自己的 searchTable 函数。

                    function searchTable() {
                     var input, filter, table, tr, td, i, txtValue;
                     input = document.getElementById("myInput");
                     filter = input.value.toUpperCase();
                     table = document.getElementById("showTable");
                     tr = table.getElementsByTagName("tr");
                     th = table.getElementsByTagName("th");
                     var tdarray = [];
                     var txtValue = [];
                     for (i = 0; i < tr.length; i++) {
                       for ( j = 0; j < th.length; j++) {
                         tdarray[j] = tr[i].getElementsByTagName("td")[j];
                       }
                       if (tdarray) {
                         for (var x = 0; x < tdarray.length; x++) {
                           if (typeof tdarray[x] !== "undefined") {
                              txtValue[x] = tdarray[x].textContent || tdarray[x].innerText;
                              if (txtValue[x].toUpperCase().indexOf(filter) > -1) {
                                tr[i].style.display = "";
                              } else {
                                tr[i].style.display = "none";
                              }
                           }
                         }
                       }
                     }
                    }
                    
                    
                    <input style="width: 485px;" type="text" id="myInput"  class="search-box" onkeyup="searchTable()" placeholder="Suche..">
                      
                    
                    
                    <table id="showTable">
                      <thead>
                        <tr>
                        </tr>
                      </thead>
                      <tbody>
                      </tbody>
                    </table>
                    

                    【讨论】:

                      【解决方案16】:

                      这是我的例子

                      <input class="form-control data-search" type="text" name="employee_quick_search" data-table=".employee-table" placeholder="Kiirotsing" value="see">
                      
                      <table class="employee-table">
                      
                      
                      $("tbody tr", 'table.search-table').filter(function (index) {
                      
                      //IF needed to show some rows
                      /*
                                  if (index == 0 || index == 1)
                                      return;
                      */
                      
                                  var inputValueFound = false;
                      //input search
                                  $('input,textarea,select', this).each(function(){
                      
                                      if( $(this).val().toLowerCase().indexOf(value) > -1 )
                                          inputValueFound = true;
                                  });
                      //text search
                                  $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1 || inputValueFound);
                              });
                      

                      【讨论】:

                        【解决方案17】:

                        在这里你可以使用这个 JQuery 代码。我个人正在使用此代码。

                        $("#ticket-search").on("keyup", function() {
                        
                            var value = $(this).val().toLowerCase();
                        
                            $("#ticket-table tr").filter(function() {
                        
                              $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                        
                            });
                        
                          });
                        

                        【讨论】:

                        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
                        【解决方案18】:

                        以下是我搜索 html 表格的方式:

                        ...
                        function filterTo(input, table) {
                        var tr = document.getElementById(table).getElementsByTagName('tr');
                        for (var i = 1; i < tr.length; i++) {
                            var td = tr[i].getElementsByTagName('td');
                            var hide = true;
                            for (var j=0; j<td.length; j++) { 
                                if (td[j].innerHTML.toUpperCase().indexOf(input.toUpperCase()) > -1) { hide=false; break } 
                            }
                            tr[i].style.display = hide ? 'none' : '';
                        } }
                        

                        【讨论】:

                          猜你喜欢
                          • 2017-02-22
                          • 2012-02-26
                          • 2017-07-11
                          • 2018-06-21
                          • 1970-01-01
                          • 2014-06-02
                          • 1970-01-01
                          • 2017-03-21
                          • 2015-11-07
                          相关资源
                          最近更新 更多