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

Guide to creating a reminder feature in NestJS

In my NestJS project, I've created a POST API to add a Date object representing the date and time for sending notifications to a mobile app. Currently, I am working on checking which reminders have been reached for all users in order to trigger remin ...

Transform Json data from JavaScript format to a format that PHP can understand

I have a collection of json files that I need to parse and extract information from in order to store it in a database using PHP. The issue I'm encountering is that these json keys do not have quotes around them, like: [{f:{v:11,ib:5,gh:"res",bfr:7, ...

Error: Unable to modify the value of a protected property '0' in the object 'Array'

I am facing a challenging issue with implementing a Material UI slider in conjunction with Redux. Below is the code for the slider component: import { Slider } from '@material-ui/core' const RangeSlider = ({handleRange, range}) => { ...

Building Unique Staircases with Three.js Geometry

I have been working on creating a custom three.js geometry for round staircases, but I seem to have made some errors with the vertices and indexes of the steps. Below is an example staircase that utilizes my custom geometry: https://i.sstatic.net/uQXvP.j ...

JavaScript: unable to locate information within JSON reply

Looking to develop a Twitter bot utilizing the Twitter and Spotify APIs. Making progress, but encountered an issue I can't tackle alone: Seeking the artist and song name of the top 1 track from the top 50 Spotify songs. Upon sending a request to the ...

The placeholder feature seems to be malfunctioning when it comes to entering phone numbers in a react

I am working on a MUI phone number form field. I want the placeholder to show up initially, but disappear when the user starts typing. How can I achieve this functionality in my code? import React from "react"; import MuiPhoneNumber from " ...

Troubleshooting problem with MongoDB queries within a for loop

I have an array of user emails obtained from the post data. My goal is to find the _id associated with each email. Here's the for loop I attempted: var studentIds = []; for (var i = studentEmails.length - 1; i >= 0; i--) { var email = studentEm ...

Error encountered: "Localhost at VScode is refusing port 8080 for Cold

After coding in Visual Studio Code, I encountered an issue where Chrome debug was not connecting to localhost. How can I resolve this problem by adjusting the settings in launch.json? Check out the code snippet from launch.json below: // Use IntelliSense ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...

Is there a way to have one element automatically expand when another is selected?

I'm currently utilizing the date and time picker from . However, I need some assistance with the current setup. Currently, the date and time pickers are in separate input fields. In order to select a date, I have to click on the Date input field, and ...

Whenever I attempt to retrieve a div, I encounter an uncaught type error, specifically stating that it cannot read the property length of

As I work on integrating notifications into my rails app, I am closely following a tutorial available at Everything progresses smoothly until the point where I attempt to use JavaScript to fetch the notifications div and append notifications from a JSON E ...

When selecting an option from jQuery autocomplete, the suggestions data may not always be returned

I have a question about the jQuery autocomplete feature. In my code snippet below, I have an input with the ID aktForm_tiekejas that uses the autocomplete function: $('#aktForm_tiekejas').autocomplete({ serviceUrl: '_tiekejas.php', wid ...

Encountering a Jquery 404 error while attempting to locate a PHP file through Ajax requests

I've been struggling with this issue for the past couple of hours, but I just can't seem to get it fixed. Here's my current file setup: classes -html --index.html --front_gallery.php -javascript --gallery.js I've been following a tuto ...

Unable to Trigger onClick Event with react-bootstrap Navbar Dropdown in Combination with react-router-dom

In my React application with react-bootstrap, I have a Navbar component that displays a dropdown menu for different brands. However, I noticed that the second brand option (Tommy Hilfiger) is always the one active by default, as if it is automatically cl ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

How can I load a function from the HTML file that is being loaded using .load() in jQuery?

Within my main window main.html, there is a div button that, when clicked, loads another html file into a large div. This is achieved using the .load() function: $('#mainpanel').load("search.htm"); The "search.htm" file contains a function cal ...

Harnessing the power of the bluebird promise library

Within myPeople function, there is a promise function being called as shown below: var myPeople = function(){ var go; return new Promise (function(resolve){ User .getPeople() .then(function(allPeople){ ...

Using the spread syntax to eliminate a property from an object within a ReactJs element

I'm trying to figure out if it's possible to remove a specific object property using spread syntax when rendering a React component. I want to achieve this without adding too much extra code. Currently, I am utilizing {reset,...inputName} In my ...

The challenge of handling scopes in Angular-seed

I am currently facing a challenge with creating a pre-routeProvider post. The problem I'm encountering is that $http is coming up as undefined, even though I am passing it to the function as per my understanding. I have made sure to declare angular.js ...

Numerous operations included in a JavaScript document

Looking to enhance my JS file by adding multiple functions, but I'm having trouble as I'm not very familiar with JavaScript. Here's what I've got so far. $(function(){ $('.incentives').hide(); $('.incentives-click&a ...