Is there a way to determine the count of visible items within a filtered list using jQuery?

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>

JSFIDDLE HERE

Answer №1

to retrieve the count, utilize the :visible selector

var count = $('.storesList  .store-block:visible').length;
$('#count').text(count);

alternatively, you can verify store-block without the hidden-store class

var count = $('.storesList  .store-block:not(.hidden-store)').length;
$('#count').text(count);

observe the operational code snippet below

var langMap = {}
$('#count').text($('.storesList  .store-block:visible').length);
$('#search-stores-box').keyup(function(){

var valThis = $(this).val().toLowerCase();
var filteredWord = getLatinWord(valThis);

   
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();
  
});
}
     var count = $('.storesList  .store-block:visible').length;
    $('#count').text(count);
   });
      
   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/2.1.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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the :after property of an element using jQuery

Is there a different approach I can take to achieve this desired outcome? Currently, the code snippet below is not yielding the expected results. $('.child_flyout:after').css({'top':'20px'}); Are there any alternative method ...

"Enhance user experience with autofocusing on form fields within an overlay

Despite spending hours searching, I can't seem to figure out a seemingly simple task. I am trying to set autofocus on a form field within an overlay that opens when a button is clicked. The overlay is implemented using basic jQuery overlay code. $(f ...

How come this function is still active even after the script has been dynamically deleted?

I am attempting to dynamically load a new script tag that will replace the jQuery content within the #clickmeDIV DIV. However, even after loading the second script tag into the #clickmeDIV DIV, the original script continues to run despite not being part of ...

Utilizing vanilla JavaScript to sort selected checkboxes into a JSON object

I've been trying to implement a difficulty filter based on checked checkboxes, but despite my ongoing search for solutions, I haven't been able to find any promising results or clear directions. Exploration I came across a code snippet that see ...

Looking for a regex pattern to update the entire directory path while keeping the file name intact, even when the last folder name

Looking for a regular expression that can replace everything except the file name in a path like this: /folder1/folder2/folder3/anything/somefile.html Can someone demonstrate how to do this using the replace method? The goal is to remove the entire path ...

Is it just me or does Img never work, no matter what the "src" is?

I am implementing Google's React example of a "Complex Grid" (located here) to create a Card-like layout. This is how the code appears: return ( <div className={classes.root}> <Paper className={classes.paper} ...

Jquery code fails to execute unless a breakpoint is set

I'm encountering a strange issue with the jquery star rating plugin. It seems that only when there's a breakpoint in my JS code will the radio buttons transform into stars; otherwise, they remain unchanged. Let me break down the code step by step ...

Uh-oh! It seems there's a mix-up. The expected input was a comma but instead, it received 'className' in Next.js

Error: There seems to be a syntax issue where an unexpected 'className' was encountered in nextjs I'm attempting to create a sign-in page with bootstrap 4, however, this error appears after I compile. The error is pointing to line 15 withi ...

Error message: Laravel Ajax function encountered an undefined variable

I am facing an issue with my ajax submission to the database. When I click the submit button, I get an "undefined" value in the return response. The problem seems to be in the controller, specifically with the 'fname' variable. I'm unsure ab ...

How can I retrieve the number of followers for a specific user ID using Laravel?

I am working with Laravel and jQuery integration public function getFollower(Request $request){ $userId = $request->get('user_id'); $artists = DB::table('artists') ->select('artists.id', 'artis ...

Converting datetime to time format

I have a datetime column in the format of YYYY-MM-DD HH:mm:ss.SSS. Is there a way to display only the time in the format of HH:mm:ss.SSS without showing the complete datetime? I have attempted the following code, but it does not seem to affect the format: ...

Unable to load circles on page refresh with amCharts Maps

I am experiencing an issue with the functionality of my amCharts maps. Whenever I refresh the page, the circles that are supposed to be displayed disappear. However, when I zoom in, the circles reappear. This problem has me puzzled, and I'm not sure ...

Steps for dynamically adding or removing multiple fields in a form

I am looking to create a form with dynamically added and deleted fields based on user requirements. For example, a person may have multiple phone numbers and email addresses. The goal is to allow users to add more than one phone number or email address if ...

When the window is resized, the scroll position is automatically reset

I came across this code snippet in a jQuery plugin named Blueberry, created by someone else. https://github.com/marktuk/Blueberry One issue I encountered with the code is that whenever the following lines are executed: //bind setsize function to window ...

What's preventing me from aligning this div in the center?

I'm trying to set up a layout with two centered columns for Tumblr posts on the left side, while keeping a sidebar on the right. Can someone help me achieve this? #wrapper /*applying styles for two columns*/ { display: inline-bloc ...

Switch between two PHP files with a toggle feature using jQuery click event

Need help with toggling between two PHP files - cab.php and d3.php. Toggling within the same file works fine, but encountering issues when trying to toggle from one file to another. function botaod2mostraesconde() { $(".wrapd2").toggle(); $( ...

reactjs error: Attempting to utilize the toLowerCase method on an undefined property during double mapping

My issue involves a JSON structure that requires mapping a function twice in a loop to access objects within an array. Once mapped, I need a textbox for searching the data list. However, I am encountering the following error: TypeError: Cannot read proper ...

Angular allows for the editing of a table by double-clicking and using an array of objects

I am dealing with an array of objects structured like this: $scope.rows = [{ num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 89 }, { num1: 56, num2: 78, num3: 8 ...

Updating select boxes using PHP, MySQL, jQuery, and AJAX

As the title suggests, I am facing issues updating select boxes and unable to find a solution. This is my HTML: <div class="col-sm-3"> <select class="form-control" id="answer9"> <option value="00">Select</option> ...

The appropriate method for transferring a prototype to an object

From my perspective, prototypes work like this: let Animal = function() { this.bark = "woof"; } Animal.prototype.barkLoud = function() { return this.bark.toUpperCase(); } let x = new Animal(); x.barkLoud() = "WOOF"; I f ...