Живой поиск по строкам таблицы

Я хочу сделать живой поиск по строкам таблицы, используя 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>

и если бы я fe. поиск Unique 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>

если бы вы, ребята, могли дать мне несколько советов о том, как сделать что-то подобное, я был бы очень признателен.

спасибо.

12 ответов


Я не уверен, насколько это эффективно, но это работает:

$("#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 применяют желтый фон к сопоставленному тексту i.e: (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();
            }
        }
    });
});

демо - применение простой подсветки



вот версия, которая ищет оба столбца.

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


Франсуа 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);
    });
});

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


Я взял ответ yckart и:

  • разнес его для удобства чтения
  • поиск без учета регистра
  • в сравнении была ошибка, которая была исправлена путем добавления .trim ()

(Если вы поместите свои скрипты в нижней части страницы ниже jQuery include, вам не понадобится готовый документ)

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 " и выполните это сравнение.


вот чистая версия Javascript с LIVE search для всех столбцов :

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";
        }
      } 
    }
  }
}

С помощью 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);

    });
});

Если какая-либо ячейка в строке содержит искомую фразу или слово, эта функция показывает, что строка иначе скрывает ее.

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

я использовал предыдущие ответы и объединил их для создания:

поиск любых столбцов скрытие строк и подсветка

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

демо здесь


вот что вы можете сделать с 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. На каждом keyup у нас есть функция jquery "поиск", которая будет запускать 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 вернет результаты, которые будут помещены в html с помощью AJAX. Здесь результат помещается в список html.

предположим, что существует фиктивная база данных, содержащая две таблицы animals и bird с двумя похожими именами столбцов "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);
    }
}

старый вопрос, но я узнаю, как это сделать быстрее. Для моего примера: у меня есть данные 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

<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";
    }
}
}

вот как я живу поиск таблицы 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' : '';
} }