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

Addressing the issue with this.setState and this.state on the Registration page

I am facing an issue with my Registration Page code. I am trying to send data to a database using this.setState and this.state, but every time I run the code, it shows an error in the onSubmit function related to this.state. Can someone please help me unde ...

What is the best way to mix up all the characters within the content of an HTML document?

<div id="contentContainer"> <h1>First Page</h1> <section id="mainSection"> <p>Lorem ipsum dolor sit amet</p> <ul> <li><a href="#">Black world</a></li> ...

Facing Problem with Angular PUT Request - "Missing required request body"

I'm encountering a problem with my Angular application when attempting to send a PUT request to the server. The error message I receive reads "Required request body is missing." Below is a snippet of the code that is relevant: Within the Child Compo ...

"Exploring the Functionality of Dropdown Menus in ASP.NET Core 1

Looking for a unique way to create a dropdown menu in ASP.Net Core 1.0? I've scoured the internet but haven't found a solution specifically tailored to this new platform. Can anyone provide guidance on how to build a large dropdown menu in Core 1 ...

The wells are surpassing the line

I'm attempting to arrange 3 Wells horizontally in one row, as shown below <div class="row" style="margin-top: 10px"> <div class="span4 well"> <h3 class="centralizado"><img src="/assets/temple.png" /> & ...

Trouble with custom font updates in Hugo using Blogdown

Recently, I've been immersing myself in Blogdown to create my own personal data blog: Using the academic theme as a base, I successfully tweaked the color scheme without any hiccups. However, despite making adjustments in my params.yaml file, none o ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

The mixin 'media-breakpoint-only' is not defined

Recently, I decided to delve into coding with Bootstrap4 and Sass. I made sure all the necessary configurations were in place for my environment/project setup: including ruby 2.3.1p112 (2016-04-26 revision 54768) [i386-mingw32] and a list of installe ...

Error: the specified item is not a valid function

As a newcomer to the world of JavaScript, I am eager to learn and explore new concepts. Currently, my focus is on centralizing the code for accessing my MySQL database within my Express JS server using promises. Below is an attempt I have made in achieving ...

Tips for repeatedly clicking a button over 50 times using Protractor

Is it possible to click the same button more than 50 times using a loop statement in Protractor? And will Protractor allow this action? Below is my locator : var nudge= element(by.xpath("//a[@class='isd-flat-icons fi-down']")); nudge.click(); ...

Using Jquery to transfer text from a form to a DIV and ensuring the final character is verified

Users can input their name on my HTML form, which will then be displayed in a DIV as part of a book title. The book title includes apostrophes (e.g. Amy's Holiday Album). However, if the user's name ends with an S, I do not want the apostrophe ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...

Unable to display Polygon using ReactNativeMaps

Having trouble displaying the polygon correctly on my screen. I suspect it's due to receiving an array of objects from my API. This is the code snippet in question: <MapView.Polygon coordinates={poligonofinale} strokeColor="#000" fillColor= ...

Cloud Firestore query error in Firebase Cloud Function despite data being present in Cloud Firestore

I'm facing an issue with my cloud function. The function is designed to query data from a Cloud Firestore collection, which exists. However, when I call the function from my iOS app, it always goes to the else statement and prints "NOT IN COLLECTION." ...

Is there a way to deactivate a tab when it's active and reactivate it upon clicking another tab in Angular?

<a class="nav-link" routerLink="/books" routerLinkActive="active (click)="bookTabIsClicked()" > Books </a> I am currently teaching myself Angular. I need help with disabling this tab when it is active ...

Verify if a checkbox is selected upon loading the page

Hey there, I have a jQuery change function set up to turn an input text box grey and read-only when a user selects a checkbox. However, I'm interested in adding a check on page load to see if the checkbox is already selected. Any suggestions for enhan ...

When working with Node.js, it is important to properly export your Oracle database connection to avoid encountering an error like "TypeError: Cannot read property 'execute

Hey there, I am a newbie when it comes to Node.js and Oracle. I've managed to create an app and establish a successful connection to the database. Now, I'm trying to figure out how to utilize the connection object throughout my application. Any s ...

Responsive design with Semantic UI

Can you please provide an example of how to design for different screen sizes using Semantic UI instead of Bootstrap? I'm looking for something similar to Bootstrap's sm and lg classes. For instance, would it look like this: <div class="col s ...

Using Flask and AngularJS: Managing Scope in a Controller with Flask Templating

Currently, my primary objective is to create a table with sortable columns. While following a tutorial and attempting to implement it into my project, I have encountered an issue. It seems that the structure of my code will not allow this functionality to ...

Is it possible to showcase HTML content within a C# string in a straightforward manner?

I am attempting to achieve a specific format, similar to the following: string html = @"Hello <b> World ! </b>"; The intended result should look like this: Hello World ! The string html can be utilized on various elements such as label, t ...