showcasing recommended options in the search bar through the use of javaScript

Hey there, I've been working on creating result suggestions for my search bar. The generation process is all set, but I'm facing an issue with displaying the elements on the HTML page.

During testing, I keep seeing ${resultItem.name}, and when I debug, it seems that the problem lies in the content of the suggestion variable within the forEach loop.

const articles = [{ name: 'toto' }, { name: 'mamam' }, { name: 'tampon' }, { name: 'TANTON' }];

const rechercheInput = document.getElementById('rechercheInput');
rechercheInput.addEventListener('keyup', function() {
  const input = rechercheInput.value;
  const result = articles.filter(item => item.name.toLocaleLowerCase().includes(input.toLocaleLowerCase()));
  let suggestion = '';
  result.forEach(resultItem =>
    suggestion += '<div class="suggestion">${resultItem.name}</div>'
  )
  document.getElementById('suggestions').innerHTML = suggestion;
})
<form method="get" action="">
  <input type="search" name="recherche" placeholder="product.." id="rechercheInput" required>
  <button class="btn waves-effect waves-light" type="submit">Recherche
            <i class="material-icons right">search</i>
          </button>
  <div id="suggestions"></div>
</form>

Answer №1

You have the option to utilize template strings in lieu of single quotes when adding the element to the suggestion key

The modification can be seen below

suggestion +=`<div class="suggestion">${resultItem.name}</div>`

const products = [
{name:'toto'},
{name:'mamam'},
{name:'tampon'},
{name:'TANTON'}
];

const searchInput=document.getElementById('searchInput');
searchInput.addEventListener('keyup',function(){
const input = searchInput.value;
const result = 
products.filter(item=>item.name.toLocaleLowerCase().includes(input.toLocaleLowerCase()));
let suggestion ='';

result.forEach(resultItem =>
    suggestion +=`<div class="suggestion">${resultItem.name}</div>`
    )
document.getElementById('suggestions').innerHTML=suggestion;
})
   <form method="get" action="">
        <input type="search" name="search" placeholder="product.." id="searchInput" 
        required>
        <button class="btn waves-effect waves-light" type="submit">Search
        <i class="material-icons right">search</i>
      </button>
      <div id="suggestions"></div>
    </form> 

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

What is causing these divs to shift apart instead of staying next to each other when the browser window is resized?

I am facing an issue with two of my divs not staying next to each other when resizing the browser window. They align perfectly when the window is wide, but as soon as I resize it to a narrower resolution, the right div moves below the left one: http://jsfi ...

Is it possible to modify the value on the src img tag prior to scraping the data

Hey everyone, check out this piece of code I have: foreach ($image as $snimka){ $url = $snimka->src; $ch = curl_init($snimka->src); $fp = fopen('images/' . basename($url), 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp ...

Send the component template and functions when triggering an expanded view in a material dialog

While striving to adhere to DRY coding principles, I've encountered a dilemma involving a particular use case. The task at hand is to display an expanded view of a component within a dialog box. This component presents JSON records in a paginated list ...

What is the best way to align a box once another one has been placed?

I have integrated both Bootstrap and Masonry plugins into my website design. The issue I am facing is that the Masonry plugin box goes under the top Bootstrap bar. I tried adding a margin-top: 50, but this resulted in a horizontal scroll bar appearing. To ...

When attempting to transmit data to the server, an error message pops up in the DevTools console of the browser. The error is displayed as "Network Error at create

I am currently utilizing React JS for the front end of my web application and PHP for the back end. When I try to send data to the server upon clicking a button on the webpage, I encounter the following error: Network Error at createError (createError.js:1 ...

Leverage the power of JavaScript validation combined with jQuery

Hello, I'm relatively new to the world of Javascript and jQuery. My goal is to create a suggestion box that opens when a user clicks on a specific button or div element. This box should only be visible to logged-in users. I have some knowledge on how ...

A guide on incorporating text into a file utilizing JSP within HTML

I am working on a project that includes a JSP file and a .txt file. The JSP file contains a text field and a button, where the user can enter a text and click the button to store it in the .txt file. I have provided my code below, but I seem to be missin ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

PHP: A guide on validating textboxes with jQuery AJAX

How can I use jQuery AJAX to validate a textbox on focusout? The validation process includes: Sending the value to a PHP page for server-side validation Displaying an alert message based on the validation result I have only impl ...

Utilizing ReactStrap: a guide to retrieving the id of the chosen dropDownItem

In my code, I have a dropdownList component with various DropdownItems: <Dropdown isOpen={this.state.dropdownOpen[3]} toggle={() => { this.toggle(3); }} > <DropdownToggle className="my-dropdown" car ...

Tips for including a header with Apollo Client in a React Native app

In my React Native application, here's how I set up the Apollo client with an upload link: My goal is to include a header with a token value that will be sent with every request. However, I've had trouble finding an example specifically for Reac ...

What is the reason behind div elements shifting when hovering over a particular element?

Currently, I have floated all my div elements (icons) to the left and margin-lefted them to create space in between. I've displayed them inline as well. However, when I hover over one element (icon), the rest of the elements move. Can you please help ...

calling object functions using additional parentheses

After reviewing the passport.js documentation, I came across this piece of code: app.get('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!u ...

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

Utilizing jQuery's nextUntil() method to target elements that are not paragraphs

In order to style all paragraphs that directly follow an h2.first element in orange using the nextUntil() method, I need to find a way to target any other HTML tag except for p. <h2 class="first">Lorem ipsum</h2> <p>Lorem ipsum</p> ...

The error message "TypeError: defineCall is not a function. require() fails" indicates that

Upon joining a new project, I encountered an issue with the database model built using Sequelize. It seems that I am unable to import more than a few files using sequelize.import before running into a TypeError: defineCall is not a function. The problem ap ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

Issue with passing props from parent component to child component in Vue.js not functioning

As a newcomer, I have been assigned a project that involves using Vuejs. In this project, there is a page that utilizes a component called DashboardCard. Each DashboardCard receives 2 props - val and icon from the parent component. https://i.stack.imgur. ...

What is the best way to organize large amounts of data into an array?

I am currently working on developing a unique version of wordle using javascript and html. In order to do this, I require a comprehensive list of all possible wordle words stored in an array format. Although I have the words listed within a document contai ...

Incorporate a 404 Not Found redirect into the getServerSideProps method in Next.js

I'm seeking guidance on best practices for handling an HTTP 404 error in a server-side rendered page when the requested page lacks a corresponding server-side resource. For instance, let's say the requested page is http://localhost:3000/places/5 ...