Search code examples
jqueryhtmlsearch-box

jquery add line with no results found


$(document).ready(function(){
  $("#ltt").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#ltt tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
if (this[0]){
    "nothing found"
}
    });

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input id="ltt" type="text" placeholder="Search..">
<br><br>
<table>
  <thead>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Birthday</th>
  </tr>
  </thead>
  <tbody id="ltt">
  <tr>
    <td>James</td>
    <td>Heier</td>
    <td>30 April 1983</td>
  </tr>
  <tr>
    <td>Sandro</td>
    <td>Key</td>
    <td>14 May 1986</td>
  </tr>
  </tbody>
</table>

i'm trying to add a line in case no match found, can you support me and tell me what i'm doing wrong? i put the whole query. Please find below the script thank you so much for your help and support


Solution

  • I would use .each() instead of .filter() since you're not filtering an array but simply taking an action on each element. Also use the named parameters instead of this as I mentioned in a comment.

    Finally, you can simply count how many elements end up being visible, and then hide or show the "nothing found" message as needed.

    Also note that in your original code, the "nothing found" string would never up being displayed, because it is just a string in your JavaScript code and never makes it into the DOM.

    Something along these lines should work. You will want to improve the presentation from my rough example, for example the table headers still appear and move around when "Nothing found" is shown. But it should give you some ideas of where to go from here:

    $(document).ready(function(){
      $("#ltt").on("keyup", function(event) {
        var value = $(event.target).val().toLowerCase();
        var count = 0;
        $("#ltt tr").each(function(index, element) {
          var show = $(element).text().toLowerCase().indexOf(value) > -1;
          $(element).toggle(show);
          if( show ) {
            count++;
          }
        });
        $('#nothing').toggle( count === 0 );
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <input id="ltt" type="text" placeholder="Search..">
    <br><br>
    <table>
      <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Birthday</th>
      </tr>
      </thead>
      <tbody id="ltt">
      <tr>
        <td>James</td>
        <td>Heier</td>
        <td>30 April 1983</td>
      </tr>
      <tr>
        <td>Sandro</td>
        <td>Key</td>
        <td>14 May 1986</td>
      </tr>
      </tbody>
    </table>
    <div id="nothing" style="display: none;">
        Nothing found
    </div>