Reputation: 23
I have some data stored in a table I would like to filter using Javascript. I type my filter string in an input field and show only rows which match.
But now, I would like to do this : for example, if I type value1|value2
in my filter field, I want only rows which match with these 2 strings (value1 AND value2
). I've tried many ways to do it but no one does exactly what I want ...
Here is an example of what I use to filter (works with one string) :
function filterFromName(text) {
// Variables
var filter, tableData, tr, td, i;
filter = text.toUpperCase();
tableData = document.getElementById('data_values');
tr = tableData.getElementsByTagName('tr');
// For each table row, hide those who don't match the search text
for (i = 0; i< tr.length; i++) {
td = tr[i].getElementsByTagName('td')[1]; // query the Alias column
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1)
tr[i].style.display = "";
else
tr[i].style.display = "none";
}
}
}
Is there a way to adapt this piece of code to do what I want?
Upvotes: 1
Views: 927
Reputation: 68413
But now, I would like to do this : for example, if I type "value1|value2" in my filter field, I want only rows which match with these 2 strings (value1 AND value2).
You need to change your logic as (comments inline)
function filterFromName(text) {
var tableData, tr, td, i;
var filterParams = text.toUpperCase().split( "|" ); //split by | to get array of search parameters
tableData = document.getElementById('data_values');
tr = tableData.getElementsByTagName('tr');
// For each table row, hide those who don't match the search text
for (i = 0; i< tr.length; i++) {
td = tr[i].getElementsByTagName('td')[1]; // query the Alias column
if (td) {
var tdValue = td.innerHTML.toUpperCase();
var isMatched = filterParams.filter( function( val ){ return tdValue.indexOf( val ) > -1 }); //check if any val in filterParam array is matching the tdValue
if ( isMatched.length ) //check length of filtered resultset
tr[i].style.display = "";
else
tr[i].style.display = "none";
}
}
}
Upvotes: 1