F. Flores F. Flores - 3 months ago 7
HTML Question

Show message when RowFilter doesn't match

I'm creating a RowFilter with JavaScript for my table, everything works fine but when text from search input doesn't match I would like to show a message (No results found... inside the table in a < td >) but I don't know exactly how to do that, here is my HTML:

<div class="container">
<input class="form-control" type="text" id="buscar" placeholder="search..." />
<hr />
<div class="row">
<table class="table table-striped" id="Tabla">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Level</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>This is my name</td>
<td>Level Master 45</td>
</tr>
<tr>
<td>2</td>
<td>This is my name number 2</td>
<td>Level Master 1</td>
</tr>
<tr>
<td>3</td>
<td>This is my name number 3</td>
<td>Level Mastermind 4</td>
</tr>
</tbody>
</table>

<hr />

</div>

</div>


And here is the JS:

$(document).ready(function () {
RowFilter();
});

function RowFilter() {
var busqueda = document.getElementById('buscar');
var table = document.getElementById("Tabla").tBodies[0];

buscaTabla = function() {
texto = busqueda.value.toLowerCase();
var r = 0;
while (row = table.rows[r++]) {
if (row.innerText.toLowerCase().indexOf(texto) !== -1)
row.style.display = null;
else {
row.style.display = 'none';
}
}
}

busqueda.addEventListener('keyup', buscaTabla);

}


And here is a demo in JSFiddle

Working Example

I tried to show an alert in the else part of the while in the js function but the alert is shown a lot of times (while row = table.rows[r++]). Thanks in advance.

Answer

Here's a fork of your original JSFiddle that displays a message when there are no search results.

https://jsfiddle.net/reid_horton/yg98jqcj/

First, add the element you wish to display to the HTML above (or in) your table.

<div id="no-results">
  No results!
</div>

Set it to hide by default.

#no-results {
  display: none;
}

To detect when there are no search results, change your loop to this.

var didMatch = false;
var r = 0;
while (row = table.rows[r++]) {
  if (row.innerText.toLowerCase().indexOf(texto) !== -1) {
    row.style.display = null;
    didMatch = true;
  } else {
    row.style.display = 'none';
  }
}
if (!didMatch) {
    noResults.style.display = 'block';
} else {
    noResults.style.display = 'none';
}

The didMatch variable is used to keep track of if any results matched. When it is true, you hide #no-results, and when it is false, you show it.