Reputation: 644
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.
Upvotes: 36
Views: 153153
Reputation: 113
code script
<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>
html :
<input id="myInput" type="text" placeholder="Search..">
Upvotes: 0
Reputation: 13
You can conduct a live search in a table. Here's an example of searching any keywork in a search box to find output in a table.
$("#serachname").on("keyup", function () {
var value = $(this).val();
$(".search-keyword").each(function (index) {
$row = $(this);
var id = $row.find("th").text().trim();
if (id.indexOf(value) == -1) {
$row.hide();
} else {
$row.show();
}
});
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group mx-sm-3 mt-3">
<input type="text" class="form-control" id="serachname" placeholder="Search ">
</div>
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr class="search-keyword">
<th scope="row">1</th>
<th>T1</th>
<th>P1</th>
<th>V1</th>
</tr>
<tr class="search-keyword">
<th scope="row">2</th>
<th>T2</th>
<th>P2</th>
<th>V2</th>
</tr>
<tr class="search-keyword">
<th scope="row">3</th>
<th>T3</th>
<th>P3</th>
<th>V3</th>
</tr>
</tbody>
</table>
Upvotes: 0
Reputation: 13
I tried to use the below example. but I didn't find the first record. so tried to change a little code after my search code worked.
$("#serachname").on("keyup", function () {
var value = $(this).val();
$(".search-keyword").each(function (index) {
$row = $(this);
var id = $row.find("th").text().trim();
if (id.indexOf(value) == -1) {
$row.hide();
}
else {
$row.show();
}
});
});
Example => https://codepen.io/hardik-solgama/pen/vYdrWMj
Upvotes: 0
Reputation: 35
Here you can use this JQuery code. I'm personally using this code.
$("#ticket-search").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#ticket-table tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
Upvotes: 0
Reputation: 11
<!--code for table search start-->
<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><!--code for table search end-->
Upvotes: 1
Reputation: 89
This is my example
<input class="form-control data-search" type="text" name="employee_quick_search" data-table=".employee-table" placeholder="Kiirotsing" value="see">
<table class="employee-table">
$("tbody tr", 'table.search-table').filter(function (index) {
//IF needed to show some rows
/*
if (index == 0 || index == 1)
return;
*/
var inputValueFound = false;
//input search
$('input,textarea,select', this).each(function(){
if( $(this).val().toLowerCase().indexOf(value) > -1 )
inputValueFound = true;
});
//text search
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1 || inputValueFound);
});
Upvotes: 0
Reputation: 1
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>
Upvotes: 0
Reputation: 888
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>
Upvotes: 2
Reputation: 1
$("#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
Upvotes: 0
Reputation: 19
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' : '';
} }
Upvotes: -1
Reputation: 13202
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";
}
}
}
}
}
Upvotes: 6
Reputation: 1072
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";
}
}
}
Upvotes: 2
Reputation: 101
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.
Upvotes: 4
Reputation: 3580
I used the previous answers and combine them to create:
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
Upvotes: 1
Reputation: 478
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();
}
}
});
});
Upvotes: 1
Reputation: 3752
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);
});
});
Upvotes: 1
Reputation: 3862
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);
}
}
Upvotes: 1
Reputation: 22339
I'm not sure how efficient this is but this works:
$("#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();
}
}
});
});
I did add some simplistic highlighting logic which you or future users might find handy.
One of the ways to add some basic highlighting is to wrap em
tags around the matched text and using CSS apply a yellow background to the matched text i.e: (em{ background-color: yellow }
), similar to this:
// 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();
}
}
});
});
Demo - applying some simple highlighting
Upvotes: 69
Reputation: 593
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/
Upvotes: 34
Reputation: 33408
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/
Upvotes: 17
Reputation: 32655
I took yckart's answer and:
(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.
Upvotes: 4