I am struggling with a jQuery function that filters a list of 4 divs based on user input in an input field. My goal is to display and count the number of filtered results each time a key is pressed. I am using the "size" function to get the total number of results, but I'm encountering issues with getting the correct count.
Here's my code:
var langMap = {}
$('#search-stores-box').keyup(function(){
var valThis = $(this).val().toLowerCase();
var filteredWord = getLatinWord(valThis);
var count = $('.storesList .store-block').size() - $('.storesList .hidden-store').size();
$('#count').text(count);
if(filteredWord == ""){
$('.storesList .store-block').show();
$('.storesList .store-block').removeClass('hidden-store');
} else {
$('.storesList .store-block').each(function(){
$('.storesList .store-block').addClass('hidden-store');
var text = $(this).text().toLowerCase();
text = getLatinWord(text);
(text.indexOf(filteredWord) > -1 ) ? $(this).show() : $(this).hide();
});
}
});
function getLatinWord(word){
return word.split('').map(function(character){
if (langMap[character]) {
return langMap[character];
}
return character;
}).join('');
}
.results-box {
margin-bottom:10px;
overflow:hidden;
display:inline-block;
}
.search-area {margin-bottom:10px;}
#count {display:inline-block;}
.store-block {
width:80%;
margin-bottom:10px;
padding:5px;
background:#e5e5e5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="results-box">Number of stores:
<div id="count"></div>
</div>
<div class="search-area">
<input placeholder="Type a store name..." id="search-stores-box" type="text" />
</div>
<div class="storesList">
<div class="store-block">Apple Store</div>
<div class="store-block">Microsoft Store</div>
<div class="store-block">Motorola Store</div>
<div class="store-block">Nokia Store</div>
</div>