web-dev-qa-db-fra.com

Recherche en direct à travers les lignes de la table

Je veux faire une recherche en direct dans les lignes du tableau, en utilisant jQuery, le mot "en direct" est la clé, car je veux taper les mots-clés dans la saisie de texte, sur le même site et je voudrais que jQuery soit automatiquement trié ( ou supprimez ceux qui ne correspondent pas à la requête) aux lignes de la table.

Voici mon 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>

Et si je le ferais. Si vous effectuez une recherche par le Unique ID, les seules lignes commençant par le numéro indiqué pour l’ID unique doivent apparaître. Fe. si je tape '2' dans la zone de saisie de la recherche, les lignes suivantes doivent rester, car elles commencent par 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>

Si je voudrais taper 24, alors il ne devrait y avoir qu'une seule ligne visible car elle commence par le 24:

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

Si vous pouviez me donner des conseils sur la manière de procéder, je vous en serais très reconnaissant.

Je vous remercie.

25
Sapp

Je ne suis pas sûr de son efficacité, mais cela fonctionne:

$("#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 - Recherche en direct sur table


J'ai ajouté une logique de mise en évidence simpliste qui pourrait vous être utile, à vous ou aux futurs utilisateurs.

Une des façons d'ajouter une mise en surbrillance de base consiste à envelopper les balises em autour du texte correspondant et à l'aide de CSS, appliquez un arrière-plan jaune au texte correspondant i.e: (em{ background-color: yellow }), semblable à ceci:

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

Démo - appliquant une mise en évidence simple


54
Nope

Voici une version qui recherche les deux colonnes.

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

démo: http://jsfiddle.net/rFGWZ/369/

24
rewon

François Wahl approche , mais un peu plus court:

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

15
yckart

J'ai pris la réponse de Yckart et:

  • espacé pour la lisibilité
  • recherche insensible à la casse
  • il y avait un bogue dans la comparaison qui a été corrigé en ajoutant .trim ()

(Si vous mettez vos scripts au bas de votre page, sous l'inclusion de jQuery, vous n'avez pas besoin de document ready)

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>

Si vous voulez prolonger cela, faites-le itérer sur chaque 'td' et faites cette comparaison.

4
Michael J. Calkins

Voici la version Javascript pure avec Recherche en direct pour 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";
        }
      } 
    }
  }
}
3
Natesh bhat

Vieille question mais je trouve comment faire plus vite. Pour mon exemple: j'ai environ 10k de données dans mon tableau, donc j'ai besoin d'une machine de recherche rapide.

Voici ce que j'ai fait:

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

J'espère que ça aide quelqu'un.

2
Kafus

En utilisant la réponse de yckart , je l'ai fait pour rechercher toute la table - tous les 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);

    });
});
1
Elnoor

J'ai utilisé les réponses précédentes et les combine pour créer:

Rechercher des colonnes en masquant les lignes et en les mettant en surbrillance

Css pour mettre en évidence les textes trouvés:

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

Démo ici

1
Behzad

Si une cellule d'une ligne contient la phrase recherchée ou le mot recherché, cette fonction indique que cette ligne la cache sinon. 

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

Sous la fonction JS, vous pouvez utiliser pour filtrer la ligne en fonction de certaines colonnes spécifiées, voir le tableau searchColumn. Il est pris de l'école w3 et un peu personnalisé pour rechercher et filtrer sur la liste donnée de la colonne.

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";
    }
}
}
0
Syed Shibli
$("#search").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("tbody tr").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });

Assomption il y a une table avec un tbody. vous pouvez également rechercher avec find ou si la table a un identifiant, vous pouvez utiliser l'identifiant

0
kikonyogo faustine

Voici quelque chose que vous pouvez faire avec Ajax, PHP et JQuery. J'espère que cela vous aide ou vous donne un début. Vérifiez la requête mysql dans php. Il correspond au modèle en commençant par le premier.

Voir la démo en direct et le code source ici.

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

Créer un champ de recherche, peut être un champ de saisie comme celui-ci.

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

Nous devons maintenant écouter ce que l'utilisateur tape dans la zone de texte. Pour cela, nous utiliserons jquery live () et l’événement keyup. Sur chaque keyup, nous avons une fonction jquery "search" qui exécutera un script php.

Supposons que nous ayons le code HTML comme celui-ci. Nous avons un champ de saisie et une liste pour afficher les résultats.

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

Nous avons un script Jquery qui écoutera l'événement keyup sur le champ d'entrée et s'il n'est pas vide, il invoquera la fonction search (). La fonction search () exécutera le script php et affichera le résultat sur la même page en utilisant AJAX.

Voici le 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;    
}

}); Dans le php, lancez une requête sur la base de données mysql. Le php renverra les résultats qui seront mis dans le HTML en utilisant AJAX. Ici, le résultat est mis dans une liste HTML.

Supposons qu’il existe une base de données fictive contenant deux tables animaux et bird avec deux noms de colonne similaires, «type» et «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);
    }
}
0
Raj Sharma