jQuery 通过表格行实时搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12433304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Live search through table rows
提问by Sapp
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'd like jQuery to automaticaly sort (or remove those who doesn't match the search query) the table rows.
我想通过表格行进行实时搜索,使用 jQuery,“实时”词是关键,因为我想在文本输入中键入关键字,在同一个站点上,我希望 jQuery 自动排序(或删除那些与搜索查询不匹配的表格行。
Here is my HTML:
这是我的 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>
And if I would fe. search by the Unique ID
, it should show the only rows that starts from the certain number for the Unique ID. Fe. if I would type '2' in the search input box, the following rows should stay, as they begin with 2
:
如果我愿意。按 搜索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>
If I would type 24
, then there should be only one row visible as it begins from the 24
:
如果我输入24
,那么应该只有一行可见,因为它从以下位置开始24
:
<table>
<tr><th>Unique ID</th><th>Random ID</th></tr>
<tr><td>24111</td><td>54364</td></tr>
</table>
If you guys could give me some tips on how to do something like this I would appreciate it so much.
如果你们能给我一些关于如何做这样的事情的提示,我将不胜感激。
Thank you.
谢谢你。
回答by Nope
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:
添加一些基本突出显示的方法之一是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- applying some simple highlighting
演示- 应用一些简单的突出显示
回答by rewon
Here's a version that searches both columns.
这是一个搜索两列的版本。
$("#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;
});
});
});
回答by yckart
Fran?ois Wahl approach, but a bit shorter:
Fran?ois Wahl 方法,但有点短:
$("#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);
});
});
回答by Natesh bhat
Here is the pure Javascript version of it with LIVE search for ALL COLUMNS:
这是它的纯 Javascript 版本,带有对 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";
}
}
}
}
}
回答by Michael J. Calkins
I took yckart's answer and:
我接受了 yckart 的回答:
- spaced it out for readability
- case insensitive search
- there was a bug in the comparison that was fixed by adding .trim()
- 将其隔开以提高可读性
- 不区分大小写的搜索
- 通过添加 .trim() 修复了比较中的错误
(If you put your scripts at the bottom of your page below the jQuery include you shouldn't need document ready)
(如果您将脚本放在页面底部的 jQuery 包含下方,则不需要准备好文档)
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>
If you want to extend this have it iterate over each 'td' and do this comparison.
如果你想扩展它,让它遍历每个“td”并进行比较。
回答by Kafus
Old question but i find out how to do it faster. For my example: i have about 10k data in my table so i need some fast search machine.
老问题,但我发现如何更快地做到这一点。对于我的示例:我的表中有大约 10k 数据,所以我需要一些快速搜索机器。
Here is what i did:
这是我所做的:
$('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";
}
}
}
})
Hope it helps somebody.
希望它可以帮助某人。
回答by Syed Shibli
Below JS function you can use to filter the row based on some specified columns see searchColumn array. It is taken from w3 school and little bit customised to search and filter on the given list of column.
在 JS 函数下方,您可以使用基于某些指定列来过滤行,请参阅 searchColumn 数组。它取自 w3 学校,并进行了一些定制,以在给定的列列表上进行搜索和过滤。
HTML Structure
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";
}
}
}
回答by Raj Sharma
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start. Check the mysql query in php. It matches the pattern starting from first.
以下是您可以使用 Ajax、PHP 和 JQuery 执行的操作。希望这对您有所帮助或给您一个开始。检查php中的mysql查询。它匹配从第一个开始的模式。
See live demo and source code here.
在此处查看实时演示和源代码。
http://purpledesign.in/blog/to-create-a-live-search-like-google/
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
创建一个搜索框,可能是这样的输入框。
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
现在我们需要聆听用户在文本区域输入的任何内容。为此,我们将使用 jquery live() 和 keyup 事件。在每个 keyup 上,我们都有一个 jquery 函数“search”,它将运行一个 php 脚本。
Suppose we have the html like this. We have an input field and a list to display the results.
假设我们有这样的 html。我们有一个输入字段和一个列表来显示结果。
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
我们有一个 Jquery 脚本,它将侦听输入字段上的 keyup 事件,如果它不为空,它将调用 search() 函数。search() 函数将运行 php 脚本并使用 AJAX 在同一页面上显示结果。
Here is the JQuery.
这是 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;
}
}); In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
}); 在php中,对mysql数据库进行查询。php 将返回将使用 AJAX 放入 html 的结果。在这里,结果被放入一个 html 列表中。
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type' and ‘desc'.
假设有一个虚拟数据库,其中包含两个表动物和鸟类,它们具有两个相似的列名称“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);
}
}
回答by Elnoor
Using yckart's answer, I made it to search for the whole table - all td's.
使用yckart's answer,我让它搜索整个表 - 所有 td's。
$("#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);
});
});
回答by user890255
If any cell in a row contains the searched phrase or word, this function shows that row otherwise hides it.
如果一行中的任何单元格包含搜索的短语或单词,此功能将显示该行,否则将隐藏它。
<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();
}
}
});
});