Search Bar With Dropdown Results

Single Dropdown with search box in it

Simply use select2 plugin to implement this feature

Plugin link: Select2

enter image description here

How to have a dropdown searchbox that filters table results?

Based on your comments, below is the updated code with search box as well as dropdown that will filter rows:

function myFunction(searchTerm) {  var input, filter, table, tr, td, i;  filter = searchTerm.toUpperCase();  table = document.getElementById("myTable");  tr = table.getElementsByTagName("tr");  // Loop through all table rows, and hide those who don't match the search query  for (i = 0; i < tr.length; i++) {    td = tr[i].getElementsByTagName("td")[0];    if (td) {      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {        tr[i].style.display = "";      } else {        tr[i].style.display = "none";      }    }  }}
var options = $("#fruitOptions");$("#myTable tr:not(.header)").each(function() { options.append($("<option />").val($(this).find("td:first-child").text()).text($(this).find("td:first-child").text()));});
$("#myInput").on('input', function() { myFunction($(this).val());});
$("#fruitOptions").on('change', function() { myFunction($(this).val());});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input type="text" id="myInput" placeholder="Search for names.."><select id="fruitOptions"><option value=''>- Please select -</option></select><table id="myTable">  <tr class="header">    <th style="width:60%;">Fruit Name</th>    <th style="width:40%;">Place of Origin</th>  </tr>  <tr>    <td>Apple</td>    <td>Asia</td>  </tr>  <tr>    <td>Black Berry</td>    <td>North America</td>  </tr>  <tr>    <td>Durian</td>    <td>SouthEast Asia</td>  </tr>  <tr>    <td>Watermelon</td>    <td>South Korea</td>  </tr></table>

HTML Dropdown Box with Search and Input

<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">


Related Topics



Leave a reply



Submit