Autocomplete Dropdown Options

I am trying to create a dependent autocomplete drop-down that displays suggestions based on any typed letter, rather than just the first letter. For example, if I type "Yo," it should show "New York" in the dropdown. Below is the code I have been using, but it currently only works with the first letters.

var states = {
  'Color': ['red', 'black', 'yellow', 'green'],
  'Numbers': ['one', 'two', 'three', 'four']
};

function match(str) {
     str = str.toLowerCase();
     clearDialog();
 for (var i = 0; i < states.color.length; i++) {

  if (states.color[i].toLowerCase().startsWith(str)) {
jQuery('.dialog').append('<div>' + states.color[i] + '</div>');

}}}

Answer №1

To find a specific color, you can use the indexOf method:

if (colors.list[i].toLowerCase().indexOf(target) !== -1) {
    jQuery('.results').append('<div>' + colors.list[i] + '</div>');
}

Alternatively, you can utilize a more modern approach using includes:

if (colors.list[i].toLowerCase().includes(target)) {
    jQuery('.results').append('<div>' + colors.list[i] + '</div>');
}

Answer №2

Have you attempted replacing .startsWith(str) with .includes(str)?

For a clearer understanding:

if (states.color[i].toLowerCase().includes(str)) {
    jQuery('.dialog').append('<div>' + states.color[i] + '</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

Refresh a particular element using javascript

I'm new to Javascript and I am trying to refresh a specific element (a div) using only Javascript when that div is clicked. I came across the location.reload() function, but it reloads the entire page which doesn't fit my requirements. Upon clic ...

Robust typed ViewData for intricate object storage

I am currently developing an ASP.NET MVC system where users can click on an ajax link to open a window with a complex flow. In order to simplify management of this intricate process, I created a ViewModel to handle the complexity. However, due to the natur ...

Install Wamp on a network drive to enable all school members to view and edit HTML and PHP files

I have recently delved into the world of servers, and although I am a beginner, I am eager to learn. Can you please guide me in the right direction? At my school, we use a 'shared drive'. To experiment with servers, I downloaded and set up a WAM ...

Instead of uploading multiple files at once, allow users to upload individual files by clicking on the table row

In my dynamic table, there are 4 columns. The first 3 columns in each row have an input type='file' where users can choose a file to upload, and the 4th column has a submit button aligned with the rows. While submitting files in the first row wor ...

What techniques can I implement to optimize the speed of this feature in JavaScript?

I have developed a feature that highlights any text within a <p> tag in red based on a user-specified keyword. The current implementation works well, but it is slow when dealing with over 1000 lines of <p>. Is there a faster way to achieve this ...

Challenges in establishing the initial connection between Express.js and MongoDB

Having spent a significant amount of time researching how to set up MongoDb in an Express/NodeJs application, I believed I had a good understanding of how to implement it efficiently. I decided to initialize my mongodbConnection in the WWW file provided by ...

Determining whether the selection in jQueryUI autocomplete was made using the ENTER key or not

Seeking assistance with implementing an autocomplete field using jQuery 1.7.2 and jQueryUI 1.8.12 to achieve the following: If a suggestion is chosen from the autocomplete list (via mouse or keyboard), execute function A If no matches are found (meaning ...

What could be causing my date variable to reset unexpectedly within my map function?

Currently, I'm utilizing a tutorial to create a custom JavaScript calendar and integrating it into a React project You can find the functional JavaScript version in this jsfiddle import { useState, useRef, useMemo } from 'react' import type ...

Upon successful registration, users will be automatically redirected to their profile page

Having trouble with the redirection to the login page from my profile page, which is an HTML file and the main page is the login page. I've tried redirecting to both pages, but it always lands in the catch block whenever a redirect is attempted. angu ...

What is the best way to incorporate messages across various channels with a Discord bot?

While browsing through the questions of other users, I stumbled upon exactly what I was looking for. My dilemma now is how to make the same bot perform similar tasks on various channels but with different titles, footers, and so on... The primary code sni ...

Failure to receive an array as the output after invoking a web service using AJAX-JSON

I am working on retrieving data from my web service in array format so that I can loop through and fetch all the necessary information. Here's what I have done so far: When I return the result in my web service, I use return json_encode($newFiles); ...

Activate the Keypress event to update the input value in React upon pressing the Enter

I am facing an issue where I need to reset the value of an input using a method triggered by onPressEnter. Here is the input code: <Input type="text" placeholder="new account" onPressEnter={(event) => this.onCreateAccount(event)}> < ...

Navigating a double entry validation in a Java script prompt while utilizing Selenium

Can someone please assist me with the following scenario: I need to complete a double entry check prompt/alert that contains two text boxes. The task is to fill in these two text boxes and then click on the OK button. Potential solutions attempted: I tr ...

Changes to the folder structure in Laravel are not reflected in Vue components

Recently, while working with Laravel and Vue.js, I came across an issue after rearranging my files to upload the project online. Now, whenever I update the Vue files, the changes don't seem to reflect. Seeking assistance from the experts in this commu ...

Data is stored in the database without the need to fetch it through the $_POST method

Can someone explain how the variables are being inserted into the database without using $_POST to retrieve them? Is this a new feature in php5 or am I just unfamiliar with this method? <!doctype html> <html> <head> <title>< ...

What steps can I take to resolve the Angular JS error message: [$injector:unpr]?

index.html <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>Angular JS</title> <script src="lib/angular.min.js"></script> ...

Issues with splicing an Angular array using pure JavaScript

Could someone please help me figure out what I'm doing incorrectly? I have some JSON data that I am converting into an array for use in an ng-repeat. Before looping through the array, I am checking the event dates against today's date and removin ...

There has been a mistake: The module '.... ode_modules erser-webpack-plugindistindex.js' cannot be found. Please ensure that the package.json file contains a correct "main" entry

After setting up Vue.js and executing npm run serve, I encountered the following error: PS C:\Amit\Demo\VUEDemo\myvue> npm run serve > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f5e1eeedfdd8a8b6 ...

simplify sending emails through WAMP and a proxy server

For the past couple of days, I've been attempting to send emails from my PHP application that's running on my PC with WAMP. I made adjustments to the php.ini file as follows: [mail function] ; For Win32 only. ; http://php.net/smtp SMTP = mail.my ...

Tips for updating DataTable data following a database update:

Struggling with this issue: I've created a view containing PrimeFaces components like <p:datatable /> and <p:contextMenu />. The contextMenu has an actionListener attribute that triggers a method in the Managed Bean to update the current ...