Home > Software design >  display of suggestion elements on the search bar using (javaScript)
display of suggestion elements on the search bar using (javaScript)

Time:12-14

Hi I created a result suggestion on my search bar, everything works on the suggestion generation process, but I can't display the elements obtained on the html page.

when testing the code, it shows me ${resultItem.name} when debugging the error is on the content of the suggestion variable in 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 >${resultItem.name}</div>'
  )
  document.getElementById('suggestions').innerHTML = suggestion;
})
<form method="get" action="">
  <input type="search" name="recherche" placeholder="product.." id="rechercheInput" required>
  <button  type="submit">Recherche
            <i >search</i>
          </button>
  <div id="suggestions"></div>
</form>

CodePudding user response:

You can use template strings instead of single quotes when appending the element to the suggestion key

The change is here

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

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 >${resultItem.name}</div>`
    )
document.getElementById('suggestions').innerHTML=suggestion;
})
   <form method="get" action="">
        <input type="search" name="recherche" placeholder="product.." id="rechercheInput" 
        required>
        <button  type="submit">Recherche
        <i >search</i>
      </button>
      <div id="suggestions"></div>
    </form> 

CodePudding user response:

Because you are not using backtick `` in suggestion = instead you used quotes

  • Related