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\
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' : '';
} }
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
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);
}
}
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'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
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>