1.- For the search based on the content of the divs, is that a good practice?
2.- When I perform a search, and then I delete all of the input, how do I return to its initial state, that is to say that all the users are shown, are there events that help me solve the problem?
$(function(){
var data = [];
$('#usuarios').children('li').each(function () {
data.push($(this).children('div').text());
});
function igualar(buscados) {
var palabras = [];
$.each(buscados, function(idx, buscado) {
palabras.push(buscado.toLowerCase());
});
return palabras;
}
function orden(a, b) {
if (a.normal > b.normal) {
return 1;
}
if (a.normal < b.normal) {
return -1;
}
return 0;
}
function existe(elem, lista){
for(var i=0;i<lista.length; i++){
if(lista[i]==elem){
return true;
}
}
return false;
}
function eliminarDivs(posibles){
$('#usuarios').children('li').each(function () {
if(!existe($(this).children('div').text(),posibles)){
var ide= $(this).children('div').attr('id');
document.getElementById(ide).parentNode.remove();
}
});
}
data = igualar(data);
data.sort(orden);
$("#nombre").on("input",function() {
var key = document.getElementById("nombre").value,
posibles = [],
lucky = false;
key =key.toLowerCase();
$.each(data, function(idx, word) {
if (word.indexOf(key) !== -1) {
posibles.push(word);
if (key === word) {
lucky = word;
}
}
});
eliminarDivs(posibles);
});
})
#usuarios li{
display:inline-block;
}
li{
width:30%;
height:100px;
text-align:center;
}
li:hover{
background:#b6b5e7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Escribe para buscar usuarios:
<input type="text" id="nombre">
<ul id="usuarios">
<li><div id="1">miesha</div></li>
<li><div id="2">ronda</div></li>
<li><div id="3">thor</div></li>
<li><div id="4">superman</div></li>
<li><div id="5">batman</div></li>
<li><div id="6">susan</div></li>
<li><div id="7">minerva</div></li>
<li><div id="8">pedro</div></li>
<li><div id="9">diana</div></li>
<li><div id="10">fedor</div></li>
</ul>