I need to filter elements from a list and show them in a result list. I made the following code:
var ele = [];
$('.search').keyup(function(event) {
var val = $(this).val().toUpperCase();
$('.title').each(function(index, el) {
if($(this).find('a').text().toUpperCase().indexOf(val) != -1){
if(val != "" && val != null){
ele.push($(this).clone());
}
}
});
$('.result').html(ele);
ele = [];
});
This is the html:
<input type="text" class="search">
<ul class="result"></ul>
<ul class="list">
<li class=""><a href="">Elder</a>
<ul>
<li class=""><a href="">Cell</a>
<ul>
<li class="title"><a href="">Apolo</a></li>
<li class="title"><a href="">megaman</a></li>
<li class="title"><a href="">goku</a></li>
</ul>
</li>
</ul>
</li>
<li>
<ul>
<li class="title"><a href=""> marcos</a></li>
<li class="title"><a href=""> weslley</a></li>
</ul>
</li>
The code works but for some reason I could not identify, it lists the same element that was already filtered while typing in the input. Where am I going wrong? Thanks!