Skip to content
Advertisement

HTML Dropdown Box with Search and Input

I’ve tried to search for what I’m after, and this is the closest I can get:

Make a Dropdown with Search Box using jQuery (by Yogesh Singh)
https://makitweb.com/make-a-dropdown-with-search-box-using-jquery/

  • It can provide a HTML Dropdown with Search capability.
  • However, what I hope to have is to have input capability as well. I.e., if nothing found, then use the user input as the result.

I tried to look at the code,

$(document).ready(function(){
 
  // Initialize select2
  $("#selUser").select2();

  // Read selected option
  $('#but_read').click(function(){
    var username = $('#selUser option:selected').text();
    var userid = $('#selUser').val();

    $('#result').html("id : " + userid + ", name : " + username);

  });
});

UPDATE: using datalist. Requirement:

  • if found, use found value as the result.
  • if nothing found, then use the user input as the result.

Maybe both are the same case, but I don’t know js well to say that.

     $(document).on('change', '#place', function () {
         $("#fax").val($("#place").val());
      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="place" list="places">
    <datalist id="places">
        <option value="WVC" label="503-882-1212"></option>
        <option value="HAM" label="612-883-1414"></option>
        <option value="WON" label="317-445-8585"></option>
    </datalist>
    <br>
    <input type="text" id="fax">

I don’t see an easy way to do that myself, as I don’t know js quite well.
It is possible, to use the user input as the result if nothing found? thx

Advertisement

Answer

<datalist> is like a separate select element and linked to the text field previous to it and simply updates the value of textfield based on what is selected. If you like to run your code based on change event on the text field, you need to read the datalist first and then pick the label from it. If there is no value, then pick the text from the textfield.

$(document).ready(function () {

    $(document).on('change', '#place', function () {
        let myString = 
               $(this).next().find("option[value='" + $(this).val() + "']").prop("label");
        myString = myString ? myString : $(this).val();
        $("#fax").val(myString);
        $(this).val(myString); //IF YOU LIKE TO SHOW SAME STRING IN TEXT FIELD TOO
    });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="place" list="places">
    <datalist id="places">
        <option value="WVC" label="503-882-1212"></option>
        <option value="HAM" label="612-883-1414"></option>
        <option value="WON" label="317-445-8585"></option>
    </datalist>
    <br>
    <input type="text" id="fax">
Advertisement