Reputation: 1350
I am working on developing a multi-column multi-word filtering search and have difficulties with two problems:
I found a table filtering techniques on SO and adjusted them in this fiddle. But this code will only filter over all the columns with one word. Typing more than one word to narrow the result (find A and B
) does not work.
The code below is my attempt to perform a multi-column multi-word search in a single box see my fiddle.
Meaning show only rows where searchphrase-1 and searchphrase-2
are present.
JS
var $orig_rows1 = $('#table tbody tr td[class = "col1"]');
var $orig_rows2 = $('#table tbody tr td[class = "col2"]');
$('#search').keyup(function() {
var $rows1 = $orig_rows1;
var $rows2 = $orig_rows2;
var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
reg = RegExp(val, 'i'),
text;
$("tr:hidden").show();
$rows1.show().filter(function() {
text = $(this).text().replace(/\s+/g, ' ');
return !reg.test(text);
}).parent("tr").hide();
});
HTML
<input type="text" id="search" placeholder="Type to search title 1">
<table class="table-striped" id="table">
<thead>
<th>Title 1</th>
<th>Title 2</th>
</thead>
<tbody>
<tr>
<td class="col1">Apple</td>
<td class="col2">Green</td>
</tr>
<tr>
<td class="col1">Grapes</td>
<td class="col2">Green</td>
</tr>
</tbody>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
</table>
Any advice would be great.
Upvotes: 0
Views: 5912
Reputation: 4904
Mistake in your code </tbody>
is placed wrong, it must be
<tbody>
<tr>
<td class="col1">Apple</td>
<td class="col2">Green</td>
</tr>
<tr>
<td class="col1">Grapes</td>
<td class="col2">Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
</tbody>
Not a perfect solution, suggestions would be greatly appreciated
Try this Demo Fiddle it has multiple words search capability made using Tag-it! plugin.
Update search for both AND and OR
Demo Fiddle with a check box to perform both operations
This is a part of the code from the linked fiddle
var search = function () {
if ($('.tagit-label').length) {
$("#table tbody tr").hide();
var toShow = [];
$('.tagit-label').each(function () {
filter = $(this).text();
$("#table tbody tr").each(function () {
if ($(this).text().search(new RegExp(filter, "i")) > 0) {
toShow.push($("#table tbody tr").index(this));
}
});
});
if ($('#chkBoth').prop("checked") && $('.tagit-label').length > 1) {
var filterShow = [];
var outputArray = [];
$(toShow).each(function (i, value) {
if (($.inArray(value, outputArray)) == -1) {
outputArray.push(value);
}
});
$(outputArray).each(function (i, value) {
var index = toShow.indexOf(value);
toShow.splice(index, 1);
});
}
$(toShow).each(function (i, value) {
$("#table tbody tr").eq(value).fadeIn();
});
} else {
$("#table tbody tr").fadeIn();
}
}
This is the result of my linked fiddle below:
Hope it helps..!!
Upvotes: 1