How to display 'no result found' on search when there is no result found, using javascript and list.js

10.1k Views Asked by At

How do i display NO RESULT FOUND after user has searched for something that is not in the list. I am using list.js and i cant figure out how to implement that?

Is there is a way i can add a JavaScript code somewhere on my code that can monitor when the table list is empty and display no result found as i search using list.js OR a better alternative?

I need a way i could tell my users that what they are searching for is not there.

var monkeyList = new List('users', {
  valueNames: ['name', 'born'],
  page: 3,
  plugins: [ ListPagination({}) ] 
});
<div id="users">
  <input class="search" placeholder="Search" />
  <button class="sort" data-sort="name">
    Sort by name
  </button>

  <ul class="list">
    <li>
      <h3 class="name">Jonny Stromberg</h3>
      <p class="born">1986</p>
    </li>
    <li>
      <h3 class="name">Jonas Arnklint</h3>
      <p class="born">1985</p>
    </li>
    <li>
      <h3 class="name">Martina Elm</h3>
      <p class="born">1986</p>
    </li>
    <li>
      <h3 class="name">Gustaf Lindqvist</h3>
      <p class="born">1983</p>
    </li>
  </ul>
<ul class="pagination"></ul>
</div>


<script src="http://listjs.com/no-cdn/list.js"></script> 
<script src="http://listjs.com/no-cdn/list.pagination.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

2

There are 2 best solutions below

4
On BEST ANSWER

Added this to the HTML:

<div class="not-found" style="display:none">Not Found</div>

It will be displayed when no matching list element is found.


Attached this event listener to listen for changes in the search box:

$('.search').on('keyup', function(event) { // Fired on 'keyup' event

  if($('.list').children().length === 0) { // Checking if list is empty

    $('.not-found').css('display', 'block'); // Display the Not Found message

  } else {

    $('.not-found').css('display', 'none'); // Hide the Not Found message

  }
});
3
On

You can also use the searchComplete callback (v1.5.0) like this:

monkeyList.on('searchComplete', function (e) {

  if (e.matchingItems.length == 0) {

    // NO RESULTS
    // jquery
    $('.not-found').show();
    // vanilla
    // by classname
    document.getElementsByClassName('className')[0].style.display = "block";
    // or by ID
    document.getElementById("elementID").style.display = "block";

  } else {

    $('.not-found').hide();
    document.getElementsByClassName('className')[0].style.display = "none";
    document.getElementById("elementID").style.display = "none";

  }

});

Hope this helps!