Tips on showcasing Javascript filter outcomes after at least 2 characters have been entered

Currently, I have implemented a filter search box that displays results as soon as a single letter is inputted. However, due to the large amount of data that needs to be filtered through, I would like the search to only show results when a minimum of two letters are entered.

I have attempted to find a solution for this issue but unfortunately, my knowledge of JavaScript is limited and I have not been successful. If there is a simple fix for this problem, I apologize for my lack of understanding.

The code I am currently using is:

document.querySelector('#searchInput').addEventListener('input', () => {
  let filter = document.querySelector('#searchInput').value.toUpperCase();
  document.querySelectorAll('#productli li').forEach(el => {
    let a = el.querySelector('a'); // gets the first only
    el.style.display = filter && (a.textContent || a.innerText).toUpperCase().indexOf(filter) != -1 ? 'list-item' : 'none';
  });
});
#productli li {
  display: none;
  list-style-type: none;
}
<input type="text" id="searchInput" placeholder="Enter your search term here">
<ul id="productli">
  <li><a href="#">Product 1</a></li>
  <li><a href="#">Product 2</a></li>
  <li><a href="#">Product 3</a></li>
</ul>
   

Answer №1

To simplify this code, you can use an if statement to test the length and return if a certain condition is met. Additionally, caching the list can improve performance.

Here is an example of how you can achieve this:

const list = document.querySelectorAll('#productli li');
document.getElementById('searchInput').addEventListener('input', function() { // now you can use "this"
  let filter = this.value.toUpperCase();
  if (filter && filter.length<3) return
  list.forEach(el => {
    let a = el.querySelector('a'); // gets the first only
    el.style.display = filter && (a.textContent || a.innerText).toUpperCase().indexOf(filter) != -1 ? 'list-item' : 'none';
  });
});
#productli li {
  display: none;
  list-style-type: none;
}
<input type="text" id="searchInput" placeholder="Enter your search term here">
<ul id="productli">
  <li><a href="#">Product 1</a></li>
  <li><a href="#">Product 2</a></li>
  <li><a href="#">Product 3</a></li>
</ul>

Answer №2

In my opinion, a simple and direct approach to accomplishing this task would be to include an if statement to check if the length of filter is greater than or equal to 2.

Additionally, if you wish to remove the filter and hide the results, you can insert an else statement where you specify el.style.display = none.

Although there may be room for improvement, it is important to always adhere to the principle of keeping it simple

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

Tips for displaying a restricted quantity of items in a list according to the number of li lines used

My approach involves using a bulleted list to display a limited number of items without a scrollbar in 'UL' upon page load. On clicking a 'more' button, I aim to reveal the remaining items with a scrollbar in UL. The following code acco ...

Exploring PHP cURL with the power of jQuery

function php_download($Url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm"); curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); curl_setopt($ch, CURLOPT_H ...

Rails 3.2 - form mistakenly submitted repeatedly

I am working on a project involving the Box model, which includes many box_videos. I have created an edit form to allow users to add box_videos to the box after it has been created: <%= form_tag "/box_videos", { method: :post, id: "new_box_videos", rem ...

Can users arrange a lineup of choices?

As a beginner, I have a task that seems pretty simple to others but not so much for me. I need to create a feature where a client can order 10 different services in the order they prefer. The idea is to use a dropdown menu or checkboxes to allow the user ...

What are the reasons for passing a global variable to a function?

Is there a difference between the two ways of writing this code? First Method: (function(i) { // Manipulate i here }(global_variable)) Second Method: (function() { // Manipulate global_variable here }()) What's the reason for passing a gl ...

How to ensure unique results when using DFS for Combination Sum?

I am currently tackling the challenge of solving LeetCode #49 Combination Sum. The objective here is to identify all the distinct combinations that add up to the specified target. While it's relatively straightforward to find permutations that result ...

Problems encountered with nested AJAX calls and the $.when.apply function handling deferred promises efficiently

I am attempting to create a triple nested series of AJAX calls, as shown in the basic structure below (fail calls have been omitted). Progress is being made up to the second level with the eventCalls. The final when.apply.done only triggers after every si ...

Incorrect Reactjs installation technique

When I try to run create-react-app on my Windows PC, only dependencies are being installed with no folders other than node_modules. Even when using Yarn, I haven't been able to progress further. Please assist and thank you in advance for any help. Thi ...

Updating a form field dynamically with AJAX in Laravel

I'm working on updating the field $medic->current based on certain logic that I have in mind. I'm quite new to using AJAX and would appreciate a little guidance to kick things off. In my code, I am calculating the difference between two dates ...

Revert the Vue State When Navigating Back in the Browser

Background In our checkout process, we redirect to Stripe after creating an order object through an API request. To prevent users from clicking the "checkout" button multiple times during this process, we toggle a variable value to show a loading icon whe ...

Is it common for Google Chrome console snapshots to have a prolonged idle time?

I noticed in Google Chrome console snapshot that my JavaScript code has a long "Idle" time. I'm not sure if this is normal. Attached is a screenshot for reference: https://i.stack.imgur.com/k0mkp.png Could this extended "Idle" time be attributed to ...

Testing the onClick event in React components using unit testing

I'm facing an issue with testing a Button wrapper component that utilizes a material-ui button. I tried writing some test code, but it's failing when trying to test the onClick event. index.tsx (ButtonWrapper Component) import React from &ap ...

Issues with HTML text areas tags not being recognized after submitting a form occur specifically in Internet Explorer

I am encountering an issue with my form. I have a textarea field within the form, and on submit, I am trying to copy the content of a div containing a table into this textarea field. However, when I send this form and the email in IE, the values appear as ...

Is Passport.js' serializeUser and deserializeUser functions never triggering?

Encountering an issue with Passport-local. It seems that neither serializeuser nor deserializeUser are being invoked. Upon researching similar problems on SO, it appears that many others facing this problem were not properly including bodyParser. Below is ...

Exploring JSON information containing colons in the labels

I am having trouble accessing JSON data in Angular that contains a colon in the label (refer to responsedata). This is the code causing issues: <li ng-repeat="i in items.autnresponse.responsedata | searchFor:searchString"> <p>{{i.autn:numhits} ...

Performing a bulk create operation with Sequelize using an array

I am facing a task where I have an array of items that need to be created in the database. My approach is to check each insertion for success. If successful, I will add the item with a flag indicating success as true in a new array (results) in JSON forma ...

Passing props from a Higher Order Component (HOC) to child components in next.js using get

I am looking to implement an HOC (Higher Order Component) for pages within my application that can provide some information stored in local storage, especially when the pages are not being server-side rendered. The challenge I'm encountering is that ...

Utilizing jQuery to target elements that are dynamically generated upon successful AJAX response

When handling dynamically created elements on ajax success, I encountered an issue. I have multiple checkboxes within a table and when the table content is replaced on ajax success, I am unable to select any new checkbox. While it is possible to trigger cl ...

`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain. I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3 ...

What advantages does withStyles offer that surpasses makeStyles?

Is there a distinct purpose for each? At what point is it more suitable to utilize withStyles instead of makeStyles? ...