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

Bootstrap-tour is incompatible with a row within a table structure

Is there a way to highlight a table row effectively? I've been struggling with it and tried using the fix mentioned in this bootstrap-tour issue here Check out this demonstration on jsFiddle: jsFiddle JAVASCRIPT $("#dialog").dialog(); var t = new ...

Angular error ReferenceError: $Value is not defined in this context

As a newcomer to AngularJS, I am facing an issue while passing a list from the HTML file to the backend for processing. The error message ReferenceError: $Value is not defined keeps popping up. Within my controller file, I have a function named test. The ...

JavaScript: AWS Amplify: Retrieving the User ID (Sub ID) Following User Registration. Post Registration, Not to Be Confused with Sign In

Currently, I am utilizing the authentication module from AWS Amplify. One question that has been on my mind is how to obtain the userID once a user signs up. While it is possible to retrieve the ID after a user signs in, I am specifically interested in re ...

The vertical and horizontal centering of linear gradients is causing them not to display

I'm having trouble with a background gradient not working properly after I centered the page both horizontally and vertically. Here is the code snippet: body { background: linear-gradient(to right, #CB356B 0%, #BD3F32 100%); margin: 0; positi ...

What is the best way to organize an Express application that handles both API requests and views?

Currently, I am in the process of developing a small application that will function as both a website and its API. To achieve this, I am utilizing Node, Express, and Webpack. The structure of my directory is organized as follows: >client |>dist ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...

Hide additional tabs on the page when the width of the tabs exceeds the page width

I am currently working on a Google module tab application. I have successfully added the tab control with drag and drop functionality within a specific area. However, I now need to limit the number of tabs displayed on the page. Regardless of the total cou ...

Exploring the ways to retrieve the returned Dynamic scope in AngularJS

There's a specific need I have - I require a single AngularJS function that can dynamically return the scope variable based on an input parameter. When it comes to controller functions, I've come across examples of how to achieve this dynamic sco ...

What is the best way to obtain the current route name within a Component?

Is it possible to retrieve the current route name in a controller? I have attempted using this.route, this.currentRoute, and this._routerRoot, but none of them seem to work. computed: { currentRoute:{ get(){ console.log(this.__routerRoo ...

When hovered over, the Dropdown Menu vanishes into thin air

I'm looking to implement a simple CSS dropdown menu on my website. Here is the code: #topNav { font-size: 12px; width: 970px; margin: 0 auto; height: 33px; background: url(images/menubg.png); /*border-bottom: solid 1px #cccccc;*/ } #topNav ul { margi ...

CSS division style not being properly implemented across entire form

I currently have an HTML form linked to a CSS file. Here is the HTML code: .css-form-group{ margin-bottom:10px; clear:both; } .css-form-group label{ font-weight: bold; } .form-input{ float: right; } .form-input:focus{ background: y ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

The framework of AngularJS modules

As I delve into structuring multiple modules for our company's application, I find myself at a crossroads trying to design the most optimal architecture. Research suggests two prevalent approaches - one module per page or a holistic 'master' ...

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...

A guide on seamlessly incorporating FlotJs functionalities into a ReactJs application

Having trouble integrating Flot charts into React due to a '$.plot' is not a function error. Here's the code I'm using: Script tags Index.html <script src="dist/libs/js/jquery.min.js"></script> <script src="dist/libs/js ...

Python script using Selenium to only print elements in an HTML page that have a specific class value and print only certain elements based on

I am currently developing a script to automatically test all the free proxies available on The website contains a comprehensive list of all available proxies, and I have successfully made my script extract and display them. However, I only want to display ...

When using momentJs to add days, it will return a moment object rather than a

How can I add 7 days to a date using momentJs in my Angular project? let startDate = "2018-08-16T02:00:00.242Z"; let newDate = moment(startDate).add(7, 'days'); I was expecting to receive the date after adding 7 days, but instead I get a momen ...

Images of equal height without compromising the resolution

How can I create responsive images with the same height inside a DIV tag, with a specified height of 200px? Any assistance would be greatly appreciated. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="desc ...

What is the best way to display a child component inside an iframe using Vue.js?

Looking to provide a live preview of an email before sending it out, I've opted to use an iframe to contain the preview and prevent style leaks. The goal is for the preview to update dynamically as the user fills out form details. How can I display a ...

Display an HTML checkbox with intricate design features

I have a simple question - how can I print a green checkbox with a white check mark (Ctrl + P) without it turning black and white? This solution currently works with Bootstrap 4.0.0, but needs to be compatible with bootstrap 3.3.7. I've managed to cr ...