2

I made this in HTML and Java script And need to make a suggestions dropdown menu appears when the user writes first letter of the word he searches for

How can I make this?

   <html>
   <body>
   <input type="text" id="myInput" autofocus="true">
   <button id="btn" onclick="myfunction()">Search</button>
   <div id="outputArea" style="font-size: 30px"></div>
    <script>
     var acronyms = {
      omg: "Oh My God",
      lol: "Lough Out Loud",
      lmao: "Lough My Age Off",
      wtf: "What This Function"
      };
       var outputAreaRef = document.getElementById("outputArea");
         function myfunction(){
         var word = document.getElementById("myInput").value.toLowerCase().trim();
       if (acronyms[word] !== undefined) {word = acronyms[word];}
      outputAreaRef.innerHTML = word;}
      </script>
     </body>
      </html>
colecmc
  • 3,133
  • 2
  • 20
  • 33

1 Answers1

1

There is a HTML5 Element that makes this really easy. The datalist tag. You can hard code the items in the list or you can use some JS to populate the list.

You can see this answer for other options on the datalist. Html datalist values from array in javascript

If you use JS to populate, here is what the markup ends up looking like: <datalist id="browsers"> <option value="Internet Explorer"> <option value="Firefox"> <!-- more items here --> </datalist>

(function(browsers) {

  function addItems (list, container) {
      list.forEach(function(item){
      const option = document.createElement('option');

      option.setAttribute('value', item);
      container.appendChild(option);
    });
  }

  const browserList = ['Internet Explorer','Firefox','Chrome','Opera','Safari','Brave'];
  addItems(browserList, browsers);
}(document.getElementById('browsers')));
<label for="autocomplete">Search for Browsers</label>
<input id="autocomplete" list="browsers">

<datalist id="browsers"></datalist>
colecmc
  • 3,133
  • 2
  • 20
  • 33