简体   繁体   中英

Searching columns html table

I have created a table with HTML and want to integrate a search box that can search 4 columns(name,name2,last_name,last_name2). I tried to find 1 column but after writing the next column is not showing anything

For example I want to:

 find name and last_name                
 find name2  and last_name2
 find last_name  and name2
 find name and last_name and name2

In others words no matter the order but after pressing the key "SPACE" is not showing results.

Here is my problem:

<input type="text" id="filter" />
 <table id="table">
    <tr>
       <td>foo</td>
       <td>1</td>
   </tr>
   <tr>
        <td>bar</td>
        <td>2</td>
   </tr>
   <tr>
        <td>some</td>
        <td>3</td>
   </tr>
   <tr>
    <td>other</td>
    <td>4</td>
   </tr>
</table>

Here is my Javascript:

 // Function
 function filterTable(value) {
  if (value != "") {
    $("#table tbody>tr").hide();
    $("#table td:contains-ci('" + value + "')").parent("tr").show();
  } else {
    $("#table tbody>tr").show();
  }
 } 

 // jQuery expression for case-insensitive filter
$.extend($.expr[":"], {
 "contains-ci": function (elem, i, match, array) {
     return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
  }
 });

// Event listener
$('#filter').on('keyup', function () {
 filterTable($(this).val());
 });

Please someone knows how to resolve this?

If you type multiple words, you have to filter each of them separately. Otherwise, you're looking for a field that has the entire space-separated string.

This splits the search string, and then shows rows that match any of them.

// Function
 function filterTable(value) {
     if (value != "") {
         $("#table td:contains-ci('" + value + "')").parent("tr").show();
     }
 }

 // jQuery expression for case-insensitive filter
 $.extend($.expr[":"], {
     "contains-ci": function (elem, i, match, array) {
         return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
     }
 });

 // Event listener
 $('#filter').on('keyup', function () {
     if ($(this).val() == '') {
         $("#table tbody > tr").show();
     } else {
         $("#table > tbody > tr").hide();
         var filters = $(this).val().split(' ');
         filters.map(filterTable);
     }
 });

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM