Search code examples
javascripthtmlautocompletehtml-datalist

Autocomplete dropdown without jQuery with links


I'm trying to use an auto complete dropdown menu using the HTML5 datalist attribute, without JQuery. But I want each suggestion, when selected, goes to an specific link (or when pressed enter, goes to the first suggestion).

What I have right now is:

<form action="www.site.com/search?q=" method="get">

 <input name="q" type="text" id="txtAutoComplete" list="languageList"/>

  <datalist id="languageList">

   <option value="OPTION1" />
   <option value="OPTION2" />

  </datalist>

</form>

In this case, it performs a search in the site. I want each option to open a specific link, OR to use value at the end of the link http://www.hitsebeats.ninja/search/label/VALUE_HERE, which goes to the correct label in Blogger. In this last case, I thought about adding the event onclick:

<datalist id="languageList" onclick='location=this.options[this.selectedIndex].value;>

    <option value='http://www.hitsebeats.ninja/search/label/OPTION1'>
    OPTION1
    </option>

</datalist>

But no success.


Solution

  • Adding another answer after OP feedback in the comments. This should redirect only if the typed option exists in the datalist.

    <script>
        function redirect(value) {
            var options = document.getElementById("languageList").options;
    
            for(var i = 0; i < options.length; i++) {
                if (options[i].value == value)
                    window.location='http://www.example.com/' + value;
            };
        }
    </script>
    <form action="http://www.example.com/search?q=" method="get">
      <input name="q" type="text" id="txtAutoComplete" list="languageList" onchange="redirect(this.value)" />
    
      <datalist id="languageList">
        <option value='OPTION1'>OPTION1</option>
        <option value='OPTION2'>OPTION2</option>
      </datalist>
    </form>
    


    First Attempt

    Using oninput on the input element you can change the location depending on what option you choose.

    <form action="http://www.example.com/search?q=" method="get">
      <input name="q" type="text" id="txtAutoComplete" list="languageList" onchange="window.location='http://www.example.com/' + this.value" />
    
      <datalist id="languageList">
        <option value='OPTION1'>OPTION1</option>
        <option value='OPTION2'>OPTION2</option>
      </datalist>
    </form>
    

    Tell me if it is what you expected or not.