How to perform a real time search and filter on a HTML table
I created these examples.
Simple indexOf search
var $rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
Demo: http://jsfiddle.net/7BUmG/2/
Regular expression search
More advanced functionality using regular expressions will allow you to search words in any order in the row. It will work the same if you type apple green
or green apple
:
var $rows = $('#table tr');
$('#search').keyup(function() {
var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
reg = RegExp(val, 'i'),
text;
$rows.show().filter(function() {
text = $(this).text().replace(/\s+/g, ' ');
return !reg.test(text);
}).hide();
});
Demo: http://jsfiddle.net/dfsq/7BUmG/1133/
Debounce
When you implement table filtering with search over multiple rows and columns it is very important that you consider performance and search speed/optimisation. Simply saying you should not run search function on every single keystroke, it's not necessary. To prevent filtering to run too often you should debounce it. Above code example will become:
$('#search').keyup(debounce(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
// etc...
}, 300));
You can pick any debounce implementation, for example from Lodash _.debounce, or you can use something very simple like I use in next demos (debounce from here): http://jsfiddle.net/7BUmG/6230/ and http://jsfiddle.net/7BUmG/6231/.
How to filter a html table using simple javascript?
You are almost there. All you needed to do was to create another for loop and iterate over all td
elements in the row, and filter using them. By doing so, if you add any columns in future, the filter will continue to work.
In the snippet below, I have done that, and slightly modified the hiding logic. I am hiding all the rows to begin with, and if a match is found, I unhide it.
for (i = 1; i < tr.length; i++) {
// Hide the row initially.
tr[i].style.display = "none";
td = tr[i].getElementsByTagName("td");
for (var j = 0; j < td.length; j++) {
cell = tr[i].getElementsByTagName("td")[j];
if (cell) {
if (cell.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
break;
}
}
}
}
function myFunction() { var input, filter, table, tr, td, cell, i, j; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); for (i = 1; i < tr.length; i++) { // Hide the row initially. tr[i].style.display = "none"; td = tr[i].getElementsByTagName("td"); for (var j = 0; j < td.length; j++) { cell = tr[i].getElementsByTagName("td")[j]; if (cell) { if (cell.innerHTML.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; break; } } } }}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myTable"> <tr class="header"> <th style="width:60%;">Name</th> <th style="width:40%;">Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Germany</td> </tr> <tr> <td>Berglunds snabbkop</td> <td>Sweden</td> </tr> <tr> <td>Island Trading</td> <td>UK</td> </tr> <tr> <td>Koniglich Essen</td> <td>Germany</td> </tr> <tr> <td>Laughing Bacchus Winecellars</td> <td>Canada</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> <td>Italy</td> </tr> <tr> <td>North/South</td> <td>UK</td> </tr> <tr> <td>Paris specialites</td> <td>France</td> </tr></table>
How can I filter a table in html through a input in dropdown?
I'll add comments in the code to explain what is going on.
let rows = Array.from(mytable.querySelectorAll('tr.content')); // An array that holds all the table rowslet cellMap = new Map(); // initialize a map rows.forEach(row => cellMap.set( row, // which we will use to store the rows in as keys Array.from(row.querySelectorAll('td')) .map(td => td.textContent) // with the rows' table cell text contents as values ));
// instead of using 'onchange' always prefer to use addEventListenermyfilter.addEventListener('change', function() { if (this.value === 'all') { // if 'All' is selected rows.forEach(row => row.hidden = false); // unhide each row return; } // otherwise const searchTerm = this.selectedOptions[0].textContent; // extract the term we're looking for rows.forEach(row => { // iterate over the table rows // and for each row, decice whether it should be hidden or not row.hidden = !cellMap.get(row).includes(searchTerm); // based on if the searchterm occurs in the cellmap for that row })});
#mytable { width: 100%; border-collapse: collapse;}
.tr { background: #808080; color: white; font-weight: bold;}
#mytable td { padding: 5px; border: 1px solid black; text-align: left;}
#optionsDiv { padding-bottom: 10px; font-weight: bold;}
#selectField { -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; border: 1px solid #ccc; font-size: 16px; height: 30px; width: 200px;}
.odd { background: #ccffeb;}
.even { background: #99FFD6;}
<!doctype html><html>
<head> <meta charset="utf-8"></head>
<body> <div class="container" style="margin-top:150px;"> <h1>Paleetu provides a variety of BPM related courses.</h1><br> <p> Please select a course from below dropdown</p> <select id="myfilter"> <option value="all">All Course</option> <option value="pegacsa">Pega CSA</option> <option value="pegacssa">Pega CSSA</option> <option value="camunda">Camunda BPM</option> </select> <table id="mytable" class="table table-bordered"> <tbody> <tr class="content"> <th>Start</th> <th>End</th> <th>Time</th> <th>Course</th> <th>Price</th> <th>Credits</th> <th>Location</th> </tr> <tr class="content"> <td>1st April 2020</td> <td>17th April 2020</td> <td>9:30AM to 12:30PM</td> <td>Pega CSA</td> <td>Rs. 14,000</td> <td>125</td> <td>Bengaluru</td> </tr> <tr class="content"> <td>1st April 2020</td> <td>17th April 2020</td> <td>1:30PM to 5:30PM</td> <td>Pega CSSA</td> <td>Rs. 14,000</td> <td>50</td> <td>Bengaluru</td> </tr> <tr class="content"> <td>1st April 2020</td> <td>17th April 2020</td> <td>1:30PM to 5:30PM</td> <td>Camunda BPM</td> <td>Rs. 14,000</td> <td>90</td> <td>Bengaluru</td> </tr> </tbody> </table> </div></body>
</html>
I need to filter table cells in real time (in html jQuery)
Thanks to blackandorangecat's link I managed to put something together.
HTML:
<label class = "text">Título:<input type="text" id="stitulo" onkeyup="filter(this, 0)" style="margin: 0 auto;"/></label>
<label class = "text">Autor:<input type="text" id="sautor" onkeyup="filter(this, 1)" style="margin: 0 auto;"/></label>
<label class = "text">Año:<input type="text" id="sano" onkeyup="filter(this, 3)" size="1" style="margin: 0 auto;"/></label>
<label class = "text">Precio máximo:<input type="text" id="sprecio" onkeyup="filterNum(this, 4)" size="1" style="margin: 0 auto;"/></label>
JavaScript:
function filter(x, y) {
// Declare variables
var input, filter, table, tr, td, i;
input = x;
filter = input.value.toUpperCase();
table = document.getElementById("catalogo");
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")[y];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
function filterNum(x, y) {
// Declare variables
var input, filter, table, tr, td, i;
input = x;
if(input.value === "") {
filter = 0.;
}
else filter = parseFloat(input.value);
table = document.getElementById("catalogo");
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")[y];
if (td) {
if ((filter >= parseFloat(td.innerHTML)) || filter === 0) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
Hopefully this will help other people too.
Real time filtering of a table
As I see you're using jQuery so why not use contains selector? You could use it after keyUp event on select tag:
$("#search").keyup(function(){
var search = this.value;
$('#table tr, #table th').show();
$('#table td:contains('+search+')').each(function(){
$(this).parent().hide();
});
});
This code will hide any cell parent (tr, th...) which have a child td containing input value . You can use this code and make it fits better your needs.
Fiddle example: http://jsfiddle.net/uby9quLo/2/
Hope it helps!
Search and filter through html table data using input textbox
First, your function search is wrong, what is !~
, and why you try to hide all the occurence you find ??
Try this:
var $rows = $('#existing tbody tr:not(:first)'); // this is the reason for table hidding like @drizzie says
$('#search').keyup(function () {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.hide().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return text.indexOf(val) != -1 ;
}).show();
});
But better look at the DEMO
Related Topics
Using HTML Script Tags to Code While They Have a Source
How to Use HTML Tags in the Options For Select Elements
How Exactly Does ≪Script Defer="Defer"≫ Work
How to Save Canvas as an Image With Canvas.Todataurl()
How to Set Html5 Required Attribute in JavaScript
Get Selected Option Text With JavaScript
Persisting the Changes of Range Objects After Selection in Html
Disable Form Auto Submit on Button Click
How to Change Div Content With JavaScript
How to Autosize a Textarea Using Prototype
How to Check Whether a Storage Item Is Set
How to Call PHP Functions by JavaScript
Why Don't Self-Closing Script Elements Work