Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter search for <ul>

I have a list of users as well:

<ul>
<li class="thumb selectable arrow light" style="margin-bottom:-5px;"
data-image="http://cdn.tapquo.com/lungo/icon-144.png">
<strong class="name">Peter <font data-count="0" style="position:relative;top:-2px;"> </font></strong> 
<small class="description">Hi!</small> 
</li>
...
</ul>

what I want is a text input each time you write a letter to display only users that start with that letter or that they might have the name. As I can do? It is with jquery but not as ...

like image 428
Jaumesv Avatar asked Mar 24 '13 11:03

Jaumesv


People also ask

How do I filter search in HTML?

Example. <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."> Note: We use href="#" in this demo since we do not have a page to link it to.

How do you filter an element in JavaScript?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

Here is a input that filters a <ul> based on the value in pure JavaScript. It works by handling the onkeyup and then getting the <li>s and comparing their inner element .name with the filter text.

jsFiddle

enter image description here

var input = document.getElementById('input');
input.onkeyup = function () {
    var filter = input.value.toUpperCase();
    var lis = document.getElementsByTagName('li');
    for (var i = 0; i < lis.length; i++) {
        var name = lis[i].getElementsByClassName('name')[0].innerHTML;
        if (name.toUpperCase().indexOf(filter) == 0) 
            lis[i].style.display = 'list-item';
        else
            lis[i].style.display = 'none';
    }
}
like image 89
Daniel Imms Avatar answered Oct 16 '22 17:10

Daniel Imms