实时搜索表格行

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

这是我的HTML:

Unique IDRandom ID
214215442
1252512556
21144666
3245466334
2411154364

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

 
Unique IDRandom ID
214215442
21144666
2411154364

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

 
Unique IDRandom ID
2411154364

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

谢谢。

我不确定这是多么有效但这有效:

 $("#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(); } } }); });​ 

演示 – 在桌上实时搜索


我确实添加了一些简单的突出显示逻辑,您或将来的用户可能会发现这些逻辑很方便。

添加一些基本突出显示的方法之一是在匹配的文本周围包装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 = '' + 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(); } } }); }); 

演示 – 应用一些简单的突出显示


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

 $("#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/

弗朗索瓦·瓦尔接近 ,但有点短:

 $("#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/

我接受了yckart的回答并且:

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

(如果你把你的脚本放在jQuery下面的页面底部,那么你就不需要准备好文档了)

jQuery的:

   

如果你想扩展它,它会迭代每个’td’并进行这种比较。

这是它的纯Javascript版本, LIVE搜索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 -1) { tr[i].style.display = ""; break ; } else { tr[i].style.display = "none"; } } } } } 

使用yckart的答案 ,我用它来搜索整个表 – 所有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); }); }); 

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

   $(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(); } } }); }); 

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

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

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

在这里演示

您可以使用Ajax,PHP和JQuery执行此操作。 希望这会有所帮助或为您提供一个开始。 检查php中的mysql查询。 它匹配从第一个开始的模式。

在此处查看实时演示和源代码。

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

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

  

现在我们需要监听文本区域中的用户类型。 为此,我们将使用jquery live()和keyup事件。 在每个keyup上我们都有一个运行php脚本的jquery函数“search”。

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

  

    我们有一个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 .= '
  • '; $html .= ''; $html .= '

    nameString

    '; $html .= '

    functionString

    '; $html .= '
    '; $html .= '
  • '; $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", "".$search_string."", $result['desc']); $display_name = preg_replace("/".$search_string."/i", "".$search_string."", $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('https://stackoverflow.com/questions/12433304/live-search-through-table-rows/urlString', $display_url, $output); // Output echo($output); } }else{ // Format No Results Output $output = str_replace('https://stackoverflow.com/questions/12433304/live-search-through-table-rows/urlString', 'javascript:void(0);', $html); $output = str_replace('nameString', 'No Results Found.', $output); $output = str_replace('functionString', 'Sorry :(', $output); // Output echo($output); } }

    老问题,但我发现如何更快地做到这一点。 对于我的例子:我的表中有大约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"; } } } }) 

    希望它对某人有帮助。

    在JS函数下面,您可以使用基于某些指定列过滤行,请参阅searchColumn数组。 它来自w3学校,并且在给定的列列表中进行了一些自定义搜索和过滤。

    HTML结构

      
    COL 1 CoL 2 COL 3 COL 4 COL 5 COL 6

      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 -1 ) { found=true; } } } if(found==true) { tr[i].style.display = ""; } else{ tr[i].style.display = "none"; } } } 

    这是我如何搜索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 -1) { hide=false; break } } tr[i].style.display = hide ? 'none' : ''; } }