[jquery] Live search through table rows

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.

Here is my 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:

<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:

<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.

This question is related to jquery search live tablerow

The answer is


This one is Best in my case

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>

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.

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.


Here's how I live search a html table:
<input type='text' onkeyup="filterTo(this.value, 'myTable')" placeholder='Search...'>
<table id='myTable'>...</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' : '';
} }

Here is the pure Javascript version of it with LIVE search for 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";
        }
      } 
    }
  }
}

$("#search").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("tbody tr").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });

Assumption there is a one table with a tbody. you can also search with find or if the table has an ID you can use the id


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.

HTML Structure

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

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

François Wahl approach, but a bit shorter:

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


I used the previous answers and combine them to create:

Search any columns by hide rows and highlighting

Css for highlight found texts:

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

Demo here


Hey for everyone still looking in 2020. I took some answers from here and made my own searchTable function.

function searchTable() {
 var input, filter, table, tr, td, i, txtValue;
 input = document.getElementById("myInput");
 filter = input.value.toUpperCase();
 table = document.getElementById("showTable");
 tr = table.getElementsByTagName("tr");
 th = table.getElementsByTagName("th");
 var tdarray = [];
 var txtValue = [];
 for (i = 0; i < tr.length; i++) {
   for ( j = 0; j < th.length; j++) {
     tdarray[j] = tr[i].getElementsByTagName("td")[j];
   }
   if (tdarray) {
     for (var x = 0; x < tdarray.length; x++) {
       if (typeof tdarray[x] !== "undefined") {
          txtValue[x] = tdarray[x].textContent || tdarray[x].innerText;
          if (txtValue[x].toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
       }
     }
   }
 }
}


<input style="width: 485px;" type="text" id="myInput"  class="search-box" onkeyup="searchTable()" placeholder="Suche..">
  


<table id="showTable">
  <thead>
    <tr>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Using yckart's answer, I made it to search for the whole table - all 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);

    });
});

I took yckart's answer and:

  • spaced it out for readability
  • case insensitive search
  • there was a bug in the comparison that was fixed by adding .trim()

(If you put your scripts at the bottom of your page below the jQuery include you shouldn't need 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>

If you want to extend this have it iterate over each 'td' and do this comparison.


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

demo: http://jsfiddle.net/rFGWZ/369/


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.

See live demo and source code here.

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.

Suppose we have the html like this. We have an input field and a list to display the results.

 <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.

Here is the 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.

Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘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);
    }
}

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.? Find a file by name in Visual Studio Code Search all the occurrences of a string in the entire project in Android Studio Java List.contains(Object with field value equal to x) Trigger an action after selection select2 How can I search for a commit message on GitHub? SQL search multiple values in same field Find a string by searching all tables in SQL Server Management Studio 2008 Search File And Find Exact Match And Print Line? Java - Search for files in a directory How to put a delay on AngularJS instant search?

Examples related to live

How to embed new Youtube's live video permanent URL? jQuery 1.9 .live() is not a function How to remove an appended element with Jquery and why bind or live is causing elements to repeat Live search through table rows jquery .live('click') vs .click() jquery live hover

Examples related to tablerow

jQuery append and remove dynamic table row Live search through table rows How to show multiline text in a table cell jQuery each loop in table row jQuery: get parent tr for selected radio button