Dropdown search results bar

$ (function() {
  var avengers = [
  "Black Widow",
  "Captain America",
  "Iron Man",
  "Thor",
  "Hulk",
  "Scarlet Witch"
 ];

document.getElementById('searchBar').onkeyup = searchDropDown;

function searchDropDown(){

    var input = document.getElementById("searchBar").value.toLowerCase();

    for (var i = 0; i < avengers.length; i++) {

       if (avengers[i].toLowerCase().includes(input)) {

          alert("Success! Avengers Assemble!")
       }
    }
  }

});

I'm encountering some issues with my JavaScript code. I'm attempting to create a search bar with a dropdown list similar to Facebook's search feature.

Would appreciate any assistance or guidance in the right direction. Thanks! :)

Answer №1

Creating a dropdown list using HTML elements is simple:

<input list="heroes" type="text" id="searchBar">
<datalist id="heroes">
  <option value="Abaddon">
  <option value="Alchemist">
  <option value="Ancient Apparition">
  <option value="Anti-Mage">
  <option value="Axe">
  <option value="Bane">
</datalist>

If you have a larger list of heroes stored in JS or JSON, you can also create the dropdown dynamically:

<input list="heroes" type="text" id="searchBar">
<datalist id="heroes"></datalist>
<script>
  var heroes = [
    "Abaddon",
    "Alchemist",
    "Ancient Apparition",
    "Anti-Mage",
    "Axe",
    "Bane",
  ];

  for (var key in heroes) {
    var optionElement = document.createElement("option");
    optionElement.value = heroes[key];
    document.getElementById("heroes").appendChild(optionElement);
  }
</script>

Answer №2

To start, make sure you include jquery on your page, as onkeyup is an event specific to jQuery.

If you want to compare a field with the value of 'search', you will need to retrieve the input value using:

<html>
    <script src="jquery.min.js"></script>
    <script>
    $( document ).ready(function() {
        var heroes = [
            "Abaddon",
            "Alchemist",
            "Ancient Apparition",
            "Anti-Mage",
            "Axe",
            "Bane",
        ];

    document.getElementById('searchBar').onkeyup = searchDropDown;

    function searchDropDown(){
        for (var i = 0; i < heroes.length; i++) {
            search = heroes[i];     
            if (search.indexOf(document.getElementById("searchBar").value)> - 1) {
                //It's recommended to use console.log rather than alert to debug more efficiently
                //To view output, press F12 in Chrome or IE, install Firebug and press F12 in Firefox, then go to the "Console" tab
                console.log("the word find:" + search);
            }
        }
    }
});

</script>
<body>
    <input type="text" id="searchBar"/>
</body>
</html>

Apologies for any language mistakes, ;)

Answer №3

If you're looking for a solution using ES6, consider using template literals (the `${}` syntax) to create each option element within a div container. Then, append the first child of each wrapper to a datalist:

const dataList = document.querySelector('#heroes');

// iterate through the array of option names
options.forEach(option => {

  // create a div wrapper for the option element
  const wrapper = document.createElement('div');

  // set the HTML content with the option value in the wrapper
  wrapper.innerHTML = `<option value="${option}">`;

  // append the first child of the wrapper to the data list
  dataList.appendChild(wrapper.firstChild)

});

Furthermore, here is a function implementation that allows you to dynamically add options to the datalist by calling it with an array of values:

const addOptions = options => {
  const dataList = document.querySelector('#heroes');
  
  options.forEach(option => { 
    const wrapper = document.createElement('div');
    wrapper.innerHTML = `<option value="${option}">`;
    dataList.appendChild(wrapper.firstChild)
  });
}

addOptions(
  ['Agility','Strength','Intelligence']
);

addOptions(
  ['One More Option']
);
<input list="heroes" type="text" id="searchBar">
<datalist id="heroes"></datalist>

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

Refreshing SQL Server data using an HTML form

In the table below: <table id="skuTable" role="grid"> <thead> <th class="skuRow">Order</th> <th>Fab. Date</th> <th class="skuRow">Norder</th> <th>Color</th> ...

Issue encountered: Object is not functioning properly with Node.js AuthenticationExplanation: A TypeError occurred

As a newcomer to Stack Overflow, I am doing my best to ask this question clearly. I am currently following a tutorial step by step ( http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local ) but I encountered an issue after the thir ...

The next-routes server.js encounters an issue: TypeError - the getRequestHandler function is not defined within the routes

I encountered an issue in my server.js file. Here is the code snippet causing the problem: const { createServer } = require('http'); const next = require('next'); const routes = require('./routes'); const app = next ({ dev: ...

Issue with adding json_encode to the end

I am trying to add the service using jQuery.each(), but it is not working in my JavaScript code? This is the output I am getting from my PHP code: { "data": [{ "service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"], "address": " ...

What is the correct way to utilize browser actions for sending keys with the "?" symbol in Protractor?

I'm facing an issue in my tests with a particular line of code browser.actions().sendKeys(Key.chord(Key.CONTROL, '?')).perform(); Interestingly, it works fine with another symbol. For example: browser.actions().sendKeys(Key.chord(Key.CONT ...

Is it possible to incorporate variables when updating an array or nested document in a mongodb operation?

Within the "myCollection" target collection, there exists a field named "japanese2". This field is an array or an object that contains another object with a property called "japanese2a", initially set to 0 but subject to change. My goal is to update this p ...

Tips for resolving asynchronous s3 resolver uploads using Node.js and GraphQL

My goal is to upload an image and then save the link to a user in the database. Below is my GraphQL resolver implementation: resolve: async (_root, args, { user, prisma }) => { .... const params = { Bucket: s3BucketName, ...

Utilize JavaScript objects to convert subscripts into HTML elements

I am currently developing an Angular 1X application where all icon labels are stored in a JS object as shown below: var labels={ ........ iconlabel_o2:"O<sub>2</sub>", iconLabel_co2:"CO<sub>2</sub>", iconLabel_h20:"H<sub ...

"Conceal navigation options in Angular JS depending on whether a user is logged in or

I am currently working on an Ionic app that has side menus with items like home, login, dashboard, and logout. For the login functionality, I am using a server API to authenticate users. When a user is logged in, I want the side menu items to display as f ...

Guide on creating a cookie in express following a successful API call

Throughout my entire application, I utilize the /api route to conceal the actual API URL and proxy it in express using the following code: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url // This ret ...

Techniques for capturing Django's output from an Ajax request

I've been trying to utilize Ajax for converting my form data to JSON and sending it to my Django view. However, I'm encountering an issue where after successful processing in the view, I am returning a template response with some context data tha ...

Encountering the "Component resolution failed" error in Vue 3 when using global components

When I declare my Vue components in the top level HTML file, everything works fine. Here is an example: <body> <div class='app' id='app'> <header-bar id='headerBar'></header-bar> ...

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

What's the Reason Behind My Array Populating on Rebuild but Not on Page Refresh?

I am currently utilizing a tech stack that includes Vue 3 with Composition API, a Pinia store, TypeScript, a SQL backend, and Fetch to retrieve data through my .NET 6 API. Within my codebase, I have a User.ts class: export default class User { userNam ...

Exploring the power of NodeJS with nested functions for conducting in-depth search

Hey there, friends! I'm currently working on a small web application using NodeJS. One of the key features in my app is a search functionality that spans across different pages. However, I have some doubts about the nested functions related to this s ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

The margin on the right side is not functioning as expected and exceeds the boundary, even though the container is using the flex display property

I'm struggling to position the rating stars on the right side without them going outside of the block. I attempted using 'display: flex' on the parent element, but it didn't solve the issue(( Currently trying to adjust the layout of t ...

I am attempting to display only the description of the button that I click on

How can I ensure that only the container pressed will display its description when the description button is clicked, instead of all mapped containers showing their descriptions? `import { useState } from "react"; export default function Se ...

Ways to expand CRA ESLint guidelines using the EXTEND_ESLINT environmental variable

Facebook's Create React App (CRA) recently introduced a new feature allowing users to customize the base ESLint rules. Recognizing that some cases may require further customization, it is now possible to extend the base ESLint config by setting the ...

Extract data from the Ajax database and automatically hide the "Load More" button when all items

Every time I fetch data from my MySQL database, I retrieve 5 items at once. $query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5"); $query->execute([$_POST["id"]]); while($row = $query -> fetch() ...