Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count visible 'li' on a search list

The code below is for a simple search. Im trying to count the visible 'li' on the list and display the total in a div "totalClasses". and then when the user search for a class update the total with only the visible classes(li).

I have tried doing this ('li:visble') but is not working.

ul = document.getElementById('myUl');
li = ul.getElementsByTagName('li');
aa = ul.getElementsByTagName('li:visible');
document.getElementById('totalClasess').innerHTML = (aa.length) + " Results";

function search() {
  var input, filter, ul, li, a, aa;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById('myUl');
  li = ul.getElementsByTagName('li');

  for (var i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName('a')[0];
    if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = '';
    } else {
      li[i].style.display = 'none';
    }
  }
}
<input type="text" id="myInput" onkeyup="search()" placeholder="Search for a class..." title="Type something">
<p class="results">Results</p>
<p id="totalClasess"></p>
<ul id="myUl">
  <li><a href="#" class="header">Section 1</a></li>
  <li><a href="#">Class 1 </a></li>
  <li><a href="#">Class 2</a></li>
  <li><a href="#">Class 3</a></li>
</ul>

DEMO: https://jsfiddle.net/52bbqor9/

like image 334
Pedro Avatar asked Jul 17 '17 19:07

Pedro


2 Answers

you need to update the count everytime you call the event handler. you can do like this:

function search()
{
   var input, filter, ul, li, a, aa;
   input  = document.getElementById('myInput');
   filter = input.value.toUpperCase();
   ul     = document.getElementById('myUl');
   li     = ul.getElementsByTagName('li'); 
   var liCount = 0;
   for(var i=0; i<li.length; i++){
        a = li[i].getElementsByTagName('a')[0];
        if(a.innerHTML.toUpperCase().indexOf(filter) > -1){ 
            li[i].style.display = '';
            liCount++;
        } else {
            li[i].style.display = 'none';
        }
    }
    document.getElementById('totalClasess').innerHTML = liCount + " Results";
}
like image 167
Dij Avatar answered Oct 21 '22 09:10

Dij


'li:visible' is not a tag, you are adding a pseudo-selector and hoping for the best, which won't work.

You could go

ul.querySelectorAll('li:visible')

If you don't care about Firefox. If you do, I'd recommend jQuery.

ul.find('li:visible');
like image 34
Seano666 Avatar answered Oct 21 '22 09:10

Seano666