0
I am using the code below to filter values within a table. It used similar code to filter items in a list and display a div if no results were found. However, I cannot display this div if I use the code below. I have tried using document.getElementById('not-found').style.display = 'block';
using a variable with boolean values, but so far I have not succeeded.
How to proceed in this case?
var $rows = $('#table tr:not(:first)');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase().split(' ');
$rows.hide().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
var textN = text.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
var matchesSearch = true;
$(val).each(function(index, value) {
matchesSearch = (!matchesSearch) ? false : ~textN.indexOf(value) || ~text.indexOf(value);
});
return matchesSearch;
}).show();
});
td, th {
border: 1px solid #000
}
#not-found {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input autofocus type="text" id="search" placeholder="Pesquisar...">
<table id="table">
<thead>
<th>Name</th>
<th>Country</th>
</thead>
<tr id='not-found'><td colspan="2">Nenhum resultado foi encontrado.</td></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>
</table>
Great, Marcos! Really, I hadn’t thought about your logic of putting the values found inside the variable
found
. Thanks a lot, man!– winiercape
@winiercape Está almost working: type "ad" in the search box to see what happens...
– hkotsubo
Thanks for the warning, @hkotsubo! I noticed that too. I’m still making some adjustments to the code, but I believe this error can be fixed by changing this line:
var $rows = $('#table tr:not(:first)');
That’s it?– winiercape
@winiercape I think it’s just put
$("#not-found").hide()
within theif($found.length)
(because if you found something, just hide this line)– hkotsubo
True! Much better, @hkotsubo! Thank you very much for the touch!
– winiercape