The JavaScript Autocomplete feature fails to clear suggestions when there is no user input detected

After watching a tutorial on using Javascript with Autocomplete and a JSON file, I implemented the code successfully. However, I encountered an issue:

  • When I clear the input field, all results from the file are displayed. I've tried adding code to clear the results, but it doesn't seem to work as intended.

The demo on JSFiddle isn't functioning properly for me due to restrictions on adding assets. Here's the section of the code that should be handling the clearing of data when the input box is empty:

if (matches.length === 0) {
matchList.innerHTML = ''; // Line 31: The results aren't cleared when the input is empty.

}

In the CSS field, I included some hardcoded data from the JSON file for your reference.

Appreciate any help, Matthttps://i.stack.imgur.com/f8FiS.jpg

Answer №1

By utilizing the onChange() method, you have the ability to monitor the total length of the keyword inputted into the input field. If the input is NULL, you can simply disregard any suggestions.

Answer №2

After experimenting with the code and conducting thorough research, I found that splitting the code into two separate events was necessary. One crucial event that was missing was triggering the code when the DOM is loaded to retrieve a list of states. Below is the updated code:

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
let states;

// Retrieve states
const getStates = async () => {
  const res = await fetch('states.json');
  states = await res.json();
};

// Filter states based on search input
const searchStates = (searchText) => {
  // Find matches for current text input
  let matches = states.filter((state) => {
    const regex = new RegExp(`^${searchText}`, 'gi');
    return state.name.match(regex) || state.abbr.match(regex);
  });

  // Clear content if input or matches are empty
  if (searchText.length === 0) {
    matches = [];
    matchList.innerHTML = '';
  }

  displayResults(matches);
};

// Display results in HTML
const displayResults = (matches) => {
  if (matches.length > 0) {
    const html = matches
      .map(
        (matt) => `<div class="card card-body mb-1">
    <h4>${matt.name} (${matt.abbr}) 
    <span class="text-primary">${matt.capital}</span></h4>
    <small>Lat: ${matt.lat} / Long: ${matt.long}</small>
   </div>`
      )
      .join('');
    matchList.innerHTML = html;
  }
};

window.addEventListener('DOMContentLoaded', getStates);
search.addEventListener('input', () => searchStates(search.value));

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

Is the callback of $.post not being executed until the loop it's contained in finishes?

I'm working on a stock table that allows users to input the quantity of stock to issue. I have a function that verifies whether or not the database has sufficient stock for each entry in the table. When debugging through the code in Chrome, I noticed ...

The server is unable to receive lists that are included within the JSON object being passed in

Below are the data contracts utilized in the function. public class ResumeSkillsListDataContract : IResumeSkillsListDataContract { public IList<ISkillDataContract> KnownSkillsList { get; set; } public IList<ISkillDataContract> BadSkill ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

Tips for including parameters in the existing URL using AngularJS

I used the $location.url() method to obtain my current URL. $location.url() returns '/details' Now, I am looking to append some parameters, such as '/details/student' How can I add '/students' to my current URL upon a ...

Transforming a Pandas DataFrame into a specialized nested JSON structure

I need to convert a Pandas Dataframe into nested json format. I attempted using the to_json function, but it only converts the entire dataframe as key-value pairs. I am unsure of how to achieve a nested json structure like this. Any assistance would be gre ...

There seems to be a malfunction in the PHP controller causing issues with the functionality

Currently, I am utilizing jQuery and PHP for my project. In the controller, I have integrated AJAX functionality. Upon the initial click action, the result is successfully retrieved (the current "show more button" is hidden and a new "show more button" is ...

Utilizing Google Maps API to automatically set an address on page load

As a beginner in using the Google Maps API, I have successfully integrated a Google Map into my project. However, I am struggling to figure out how to set specific addresses on the map. I have a list of 2,000 entries in a database, each including an addres ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...

Tips for declaring the OpenLayers map object globally

I have successfully created a map with ol 6 and added an OSM layer. Now I am trying to incorporate a vector layer that is coded in another JavaScript file, using the same 'map' object. Despite my efforts to declare it globally, it doesn't se ...

React app experiencing inconsistent loading of Google Translate script

In my React application, I have integrated the Google Translate script to enable translation functionality. However, I am facing an issue where the translator dropdown does not consistently appear on every page visit. While it sometimes loads properly, oth ...

Validation of 'e' Symbol in Input Type Number Using jQuery Validator

Hey everyone, I'm currently utilizing jQuery validator for an input field with the type of number. However, when I enter 1e1, it shows an error message saying "invalid number." Is there a way to allow numbers like 1e1 (which equals 10) without trigger ...

The JSON response is invalid due to a syntax error

Having some trouble with a JSON response: Error: Parse error on line 1: ...il.com","jpegPhoto":"/9j/4AAQSkZJRgABAQE -----------------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{&a ...

Is there a way to ensure that the table headers are printed on every page when using Google Chrome

When printing documents in Chrome browser, the table header (thead) does not appear on every page. I want to ensure that the table header is displayed on each printed page, just like it is done with IE and Firefox. However, Chrome does not support this fea ...

React-Redux - Implement a button toggle functionality to display or hide additional information

I am currently working on creating a portfolio. One of the functionalities I am trying to implement is a toggle button that will show or hide the details of a specific work when clicked. I have been learning React and Redux, so this project is a great oppo ...

What is the best way to use `JSON.parse` in jQuery to accommodate older browsers?

Is there a way to internally call the function in jQuery that performs JSON.parse? I need to support IE8 and IE9, which don't have JSON.parse available. This means I can't simply use it in my code, so I'll have to rely on an external librar ...

The null error occurs when rendering with React's state array

When I try to call an API that emits JSON, I am encountering an issue. I call the promise API function in componentDidMount, set the state, and then call it in the render method, but it always returns a null error. I need assistance, please. Interface fo ...

What is the significance of providing a sole argument to the Object () function?

Answering a related question about object constructors, what is the intention behind passing an argument to the constructor of objects and using it in this specific manner? function makeFoo(a, b) { var foo = Object.create(Foo.prototype); var res ...

Error encountered in App.js on line 29: Unable to access the property 'map' as it is undefined

Currently enrolled in the University of Helsinki Full Stack Open course, I am facing a challenging error while working on my React web app. The app retrieves data from the Rest Countries API (https://github.com/apilayer/restcountries) and I am trying to di ...

Guide to activating the isActive status on a live link within a map iteration utilizing the NEXTUI navigation bar

Check out the new NEXTUI navbar I'm using: I am having trouble setting the isActive property on the active link in my NavBar component in Next.js. I couldn't find much help on Google, so I'm hoping someone here has experience with this or k ...

Cordova Geolocation now displaying incorrect latitude and longitude values as NAN

Recently starting out with javascript and Cordova, I decided to develop a basic GPS app in Visual Studio 2015. The goal was simple: get my current position by clicking on the "CURRENT POSITION" button. Testing it in Firefox yielded positive results. Howev ...