Прямой поиск по строкам таблицы
Я хочу выполнить прямой поиск по строкам таблицы, используя jQuery, "живое" слово - это ключ, потому что я хочу набирать ключевые слова в текстовом вводе на том же сайте, и мне бы хотелось, чтобы jQuery automaticaly сортировать (или удалять тех, кто не соответствует поисковому запросу) строки таблицы.
Вот мой 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
, он должен отображать только строки, начинающиеся с определенного числа для уникального идентификатора. Fe. если я введу "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>
Если вы, ребята, можете дать мне несколько советов о том, как сделать что-то подобное, я был бы очень благодарен.
Спасибо.
Ответы
Ответ 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 применить желтый текст к совпадающему тексту i.e: (em{ background-color: yellow }
), аналогично этому:
// removes highlighting by replacing each em tag within the specified elements with it 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();
}
}
});
});
Демо - с помощью простого выделения
Ответ 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;
});
});
});
demo: http://jsfiddle.net/rFGWZ/369/
Ответ 3
подход Франсуа Валя, но немного короче:
$("#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/
Ответ 4
Я принял ответ 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" и выполните это сравнение.
Ответ 5
Вот чистая версия Javascript с LIVE для ВСЕХ КОЛОНН.:
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";
}
}
}
}
}
Ответ 6
Старый вопрос, но я узнаю, как это сделать быстрее. Для моего примера: у меня есть около 10 тыс. Данных в моей таблице, поэтому мне нужна быстрая поисковая машина.
Вот что я сделал:
$('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
Используя ответ yckart, я заставил его искать всю таблицу - все 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 text matches key and then use OR to check it for all td's
});
$(this).toggle(if_td_has);
});
});
Ответ 8
Если какая-либо ячейка в строке содержит искомую фразу или слово, эта функция показывает, что строка в противном случае скрывает ее.
<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();
}
}
});
});
Ответ 9
Я использовал предыдущие ответы и объединил их для создания:
Искать любые столбцы с помощью строковых строк и выделения
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;
});
});
});
Демо здесь
Ответ 10
Вот что вы можете сделать с Ajax, PHP и JQuery. Надеюсь, это поможет или даст вам начало. Проверьте запрос mysql в php. Он соответствует шаблону, начиная с первого.
Смотрите демо-версию и исходный код здесь.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Создайте окно поиска, может быть поле ввода, подобное этому.
<input type="text" id="search" autocomplete="off">
Теперь нам нужно прослушивать все, что пользователь вводит в текстовой области. Для этого мы будем использовать jquery live() и событие keyup. На каждой клавиатуре у нас есть функция поиска jquery, которая будет запускать php script.
Предположим, что у нас есть html. У нас есть поле ввода и список для отображения результатов.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
У нас есть JQuery script, который будет прослушивать событие 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 вернет результаты, которые будут помещены в html с использованием AJAX. Здесь результат помещается в список html.
Предположим, что есть фиктивная база данных, содержащая две таблицы животных и птиц с двумя типами имен столбцов и "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);
}
}
Ответ 11
Ниже 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";
}
}
}
Ответ 12
$("#search").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("tbody tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
Предположим, есть одна таблица с телом. Вы также можете искать с помощью поиска или, если таблица имеет идентификатор, вы можете использовать идентификатор
Ответ 13
Это лучший в моем случае
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>
Ответ 14
Вот как я живу в поиске html-таблицы:
& lt; input type = 'text' onkeyup = "filterTo (this.value, 'myTable')" placeholder = 'Поиск...'>
& lt; table id = 'myTable'>... & lt;/table>
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' : '';
} }