js30-day6-Ajax-Type-Ahead

31 Jul 2020

Introduction

Using Javascript, as letters are typed into an input box, suggestions of possible matches from a dataset of cities are listed below.

Starter

The HTML file is formatted with an input box, and is initially setup with an unordered list (UL) div with two list items. These list items will eventually get overriden with actual suggestions when text gets keyed into the input.

Process

A link is provided with a JSON, meant to represent an API endpoint. The endpoint gets fetched, which returns as a promise, upon which a then function is used which actually returns a second promise. A second nested then function is used to parse an actual JSON. This is spread into a list to finally create a list of objects, where each object is a city.

The next step is to find matches between the input and the data- specifically, by matching the input against the city and state names. This is accomplished with a map function using regex to return an array of matches. More specifically, the input is matched and then each match is formatted as a backtick string of HTML. This HTML creates a list item and so overrides the original list with a dynamically sized list of suggestions.

There’s also additional formatting done to specifically detect the exact regex match and put it into a highlight span.

All of this runs off a pair of eventListeners set for both “change” and “keyup” which allows for suggestions to change as the input is typed in.

Things Learned

Another week with a deceptively short list. Every one of these is an iceberg that I’ve barely scratched the surface of- how many mixed metaphors was that?