Utilize the arrow keys to navigate through the search suggestions

I am facing an issue with my search bar where I am unable to navigate through the suggestions using arrow keys. I have been struggling with this problem for days and would appreciate any help in resolving it.

var searchIndex = ["404 Error", "Address Bar", "Ajax", "Apache", "Autoresponder", "BitTorrent", "Blog", "Bookmark", "Bot", "Broadband", "Captcha", "Certificate", "Client", "Cloud", "Cloud Computing", "CMS", "Cookie", "CSS", "Cyberspace", "Denial of Service", "DHCP", "Dial-up", "DNS Record", "Domain Name", "Download", "E-mail", "Facebook", "FiOS", "Firewall", "FTP", "Gateway", "Google", "Google Drive", "Gopher", "Hashtag", "Hit", "Home Page", "HTML", "HTTP", "HTTPS", "Hyperlink", "Hypertext", "ICANN", "Inbox", "Internet", "InterNIC", "IP", "IP Address", "IPv4", "IPv6", "IRC", "iSCSI", "ISDN", "ISP", "JavaScript", "jQuery", "Meta Search Engine", "Meta Tag", "Minisite", "Mirror", "Name Server", "Packet", "Page View", "Payload", "Phishing", "POP3", "Protocol", "Scraping", "Search Engine", "Social Networking", "Socket", "Spam", "Spider", "Spoofing", "SSH", "SSL", "Static Website", "Twitter", "XHTML"];

var input = document.getElementById("searchBox"),
  ul = document.getElementById("searchResults"),
  inputTerms, termsArray, prefix, terms, results, sortedResults;


var search = function() {
  inputTerm.... // The code is truncated for brevity, please see original source for full content.
.search-field,
.term-list {
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
}

body {
  text-align: center;
  background: #f2f2f2;
}

.title {
  width: 100%;
  margin: 3em 0 1em;
  text-align: center;
  font-family: "Arvo", "Helvetica Neue", Helvetica, arial, sans-serif;
  font-size: 170%;
  font-weight: ....

<h1 class="title">AutoComplete Me</h1>
<input type="text" id="searchBox" class="search-field" autoFocus />
<ul id="searchResults" class="term-list hidden"></ul>

Answer №1

There is a reference to li in this context:

var li = $('li');
var liSelected;
$(window).keydown(function(e) { ...

However, at that point, there are no li elements added in the DOM yet. As a result, $('li') is returning zero elements.

Additionally, you are losing access to the li tags every time a search or keypress event occurs because you are removing the existing li elements from the DOM and adding new ones with each keypress following the search action.

Here,

var clearResults = function() {
 debugger;
  ul.className = "term-list hidden";
  ul.innerHTML = ''; // Removing all li inside the ul
}

Therefore, your original li variable is referencing outdated, removed li elements.

Solution:

To address this issue, you should update the li variable after adding new li elements within the appendResults function.

var appendResults = function() {
  clearResults();
  for (var i = 0; i < sortedResults.length && i < 5; i++) {
    var _li = document.createElement("li"),
      result = prefix +
      sortedResults[i].toLowerCase().replace(terms, '<strong>'+ terms + '</strong>');

    _li.innerHTML = result;

    ul.appendChild(_li);
  }

  li = $('li'); 
  liSelected = li.filter('.selected'); 
  $('li').click(function(e) {
    $('input').val($(this).text());
  });
  if (ul.className !== "term-list") {
    ul.className = "term-list";
  }
};

Furthermore, your search function is triggered on every keyup event, including up and down arrow key presses; make sure to handle these specific keyboard interactions.

var search = function(e) {
  if(e.which==40||e.which==38) return;
  debugger;
  inputTerms = input.value.toLowerCase();
  results = [];
  termsArray = inputTerms.split(' ');
  prefix = termsArray.length === 1 ? '' : termsArray.slice(0, -1).join(' ') + ' ';
  terms = termsArray[termsArray.length - 1].toLowerCase();

  for (var i = 0; i < searchIndex.length; i++) {
    var a = searchIndex[i].toLowerCase(),
      t = a.indexOf(terms);

    if (t > -1) {
      results.push(a);
    }
  }

  evaluateResults();
};

SNIPPET

// Remaining content of the snippet...

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

Enhancing the performance of a node.js Falcor router connecting a traditional REST API data source with a Falcor client

In my current setup, I have a traditional REST API that provides data in the following format: List of Users - GET /users.json users: [ {id: 0, name: "John Smith"}, ... ] User Details by Id - GET /users/0.json user: { id: 0, name: "Joh ...

I'm looking for help on creating a three-column table using javascript/jquery. The table should display Product, Price, and Discount (which is calculated at 20%). Can anyone

Check out this code snippet. var items = ["Laptop", "Tablet", "Smartphone", "Headphones", "Camera"]; var costs = [599.99, 299.99, 799.99, 149.99, 499.99]; displayItems = ""; totalCost = 0; for (var j = 0; j < items.length; j++) { displayItems += " ...

Formatting dates for the bootstrap datepicker

Hi there! I am currently using a bootstrap datepicker and I am attempting to retrieve the value from the datepicker text box in the format of date-month-year for my controller. However, at the moment, I am only able to obtain values in the format Tue Oct 0 ...

The dynamic fields are created by the combobox

Hey there, I have a drop-down menu (combobox) where you can select the number of adults for your booking. <select name="adult_no" id="adult_no"> <option value="">Select</option> <option value="1">1</option> <op ...

What indicators should we look for to decide if JavaScriptExecutor is needed in a Selenium C# project?

Encountering an exception with TestInChrome1 - "OpenQA.Selenium.ElementNotInteractableException: element not interactable". On the other hand, using JavaScriptExecutor in TestInChrome2 resolves the issue. Some key questions arise: What is causing the ...

Adding individual names for elements in a list using Jackson

Is there a way to assign a unique name to each element in a JSON list using JACKSON? For instance, consider the following JSON data: {"result": [ { "name": "ABC", "age": "20" },{ "name": "DEF", "age": "12" } ]} Howeve ...

Transforming the header to function similarly to the address bar in the Google Chrome mobile app

I have managed to create a fixed header that appears when the user scrolls up and disappears when they scroll down. However, I want it to behave like the address bar on the Google Chrome mobile app - remaining stationary until the top of the window reaches ...

How to simultaneously play a sound and display an alert message using JavaScript

My JavaScript code attempts to play a sound and then display an alert, but the alert always shows up first. When I click 'ok', the sound plays. How can I make it so that the sound plays before the alert appears? <script> function play() { ...

Implementing automatic redirection upon clicking using React without the need for manual clicking

I'm experiencing an issue where the page seems to automatically navigate to another page without clicking on the div. Can anyone explain why this is happening? Here's the code snippet for reference: import React, { Component } from "react&q ...

What is the method for aligning a button label to the left and an icon to the right?

I have a list of items and I want to display label text on the left and a check icon on the right. This works fine when the text is short, but when I added the textOverflow property, the icon gets hidden along with the rest of the text. Here is my list ...

Tips for aligning the dropdown menu to start from the border of the menu bar instead of displaying directly below the text

I have designed a menu-header section for my website, inspired by this image. I created a fiddle to showcase it. However, I am facing an issue where the dropdown elements for "PROGRAMS" and "WORLD OF NORTHMAN" should start from the border of the header ins ...

barchart rendered in SVG without the use of any external libraries

Creating a stacked barchart with SVG and HTML without relying on any third-party library has been quite a challenge. Despite searching extensively online, I have not come across a single resource that demonstrates how to build a stacked bar chart using pla ...

Error encountered while establishing connection with MongoClient

My server is returning the following error message: MongoClient.connect('mongodb://<'yoda'>:<'yoda69'>@ds235778.mlab.com:35778/satr-wars-quotes', (err, client) => { ^^^^^^^^^^^^^ SyntaxError ...

Using HTML to place an image tag close to an input element

I'm experiencing a strange issue where adding an img tag alongside an input and a span causes the input and span to shift downwards. <div> <span>Credit Points</span> <input type="text" name="credit_points" value="2.25"/> ...

Different ways to dynamically change tailwind colors during execution

Utilizing tailwind v3, it's feasible to customize existing colors by modifying the tailwind.config file. https://tailwindcss.com/docs/customizing-colors module.exports = { theme: { extend: { colors: { gray: { ...

Update the label on a webpage using Selenium's JavaScriptExecutor

We are currently working on a Japanese web application and are experimenting with a unique method to convert Japanese labels into English. Here is the approach we are using (though unsure if it's correct): Approach (using Selenium): Open the webpag ...

Is there a way to order the execution of two functions that each produce promises?

With my code, I first check the status of word.statusId to see if it's dirty. If it is, I update the word and then proceed to update wordForms. If it's clean, I simply update wordForms. I'm looking for advice on whether this is the correct a ...

In my Angular application, I have two div elements that I want to toggle between. When a button located in the first div is clicked, I need

I am working on a code snippet that requires me to hide div1 and display div2 when the button in div1 is clicked using Angular HTML5. Currently, I have two separate modal pop up template files and JS controllers for each of them. Instead of having two po ...

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

Vue/Vuex - using async dispatch for AJAX requests in multiple components

I am working with vuex and using a store module to load user lists in my app through ajax. After the list is loaded, it doesn't fetch again if it's already present in the vuex store. I have implemented this logic in the main application layout as ...