Search for city name in a list of cities using <li> instead of <select>
by aburayane
HTML
<ul class="city">
<li><input type="search" class="search"></li>
<div class="list">
<li id="Fes">Fes</li>
<li id="Casa">Casa</li>
<li id="Rabat">Rabat</li>
<li id="Marrakech">Marrakech</li>
<li id="Sefrou">Sefrou</li>
<li id="Agadir">Agadir</li>
<li id="Ifrane">Ifrane</li>
<li id="Oujda">Oujda</li>
</div>
</ul>
CSS
ul.city {
list-style-type: none;
}
.city {
width: 200px;
height: 100px;
overflow-y: scroll;
overflow-x:hidden;
text-transform: capitalize; // first letter in uppercase
}
.search {
text-transform: capitalize; // first letter in uppercase
}
.list {
cursor: pointer;
display: none;
}
JavaScript
/*** Search for element to loop for ***/
var child1 = $('.list').children();
console.log(child1);
/*
Output: [li#Fes, li#Casa, li#Rabat, li#Marrakech, li#Sefrou, li#Agadir, li#Ifrane, li#Oujda, prevObject: jQuery.fn.init[1]]
*/
var child2 = $('.list').children().eq(0);
console.log(child2);
/*
Output: [li#Fes, prevObject: jQuery.fn.init[8]]
*/
var child3 = $('.list').children().eq(0)[0];
console.log(child3);
/*
Output: <li id="Fes">Fes</li>
*/
var child4 = $('.list').children().eq(0)[0].tagName;
console.log(child4);
/*
Output: LI
*/
function filterList(className, value){
var setList = [];
var childs = $('.list').children().eq(0)[0].tagName;
$(childs).each(function(ind, val){
//console.log(val);
//console.log('id'+val.id);
// get ID and make small chars
var getID = val.id.toLowerCase();
setList.push(getID);
}); // end each
// clean array from empty fields
var cleanList = setList.filter(function(e){return e});
// get value and make it small chars
//var getValue = $('.'+className).val().toLowerCase();
//console.log('value '+getValue);
var row = '';
// loop through the array
$.each( cleanList, function( x, y ){
//console.log('x '+x);
//console.log('y '+y);
//console.log('val '+getValue);
//var chk = $.inArray( getValue, y );
var chk = y.indexOf(value);
//console.log(chk);
if(chk > -1){
// do not set var row
row += '<li id="'+y+'">'+y+'</li>';
$('.list').html(row).show();
} else {
$('.list').hide();
$('.list').html(row).show();
}
}); // end each
} // end filterList()
$('.search').on('keyup', function(){
var value = $(this).val();
filterList('city', value);
});
$('.search').on('click', function(){
$('.list').show();
});
$('.list').click(function(e){
var li = $(e.target);
var getTxt = li.text();
//console.log('text '+getTxt);
$('.search').val(getTxt);
$('.list').hide();
//$('.list').show();
});
/*
$('.search').on('keyup', function(){
var setList = [];
$('li').each(function(ind,...