Adnix
Adnix

Reputation: 47

How to select the first option in filtered html select field

My code:

<input class="form-control" id="myInput" type="text" placeholder="Search.."/>

<select autofocus="True" class="form-control  form-select select" id="asortyment" name="asortyment">
  <option value="493">Berlin</option>
  <option value="494">Warsaw</option>
  <option value="495">New York</option>
  <option value="496">Moscow</option>
  <option value="497">London</option>
  <option value="498">Paris</option>
  <option value="499">Wien</option>
</select>

script

$(document).ready(function(){
  $("#myInput").on("keyup", function() {
   
    var value = $(this).val().toLowerCase();
    var asortyment_tmp = document.getElementById('asortyment');
    $("#asortyment option").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });

After typing any letter, select is filtered but the previous option doesn't change automatically.

I tried almost everything. Select is changing after setting selectedIndex but I if I set it to 0 the value change to the first option, but before the list was filtered.

https://jsfiddle.net/Lxd51ans/3/

Upvotes: 1

Views: 78

Answers (1)

Zaedonn
Zaedonn

Reputation: 46

I think the biggest confusion is that typically when setting selects, you do so by the value (and you use numbers for values here). Here is my amendment to your code that should get you on the right track (but will still need some customization to make it right for your scenario).

$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    if(value.length==0){
      $('#asortyment').prop('selectedIndex',0);
      return;
    }
    var asortyment_tmp = document.getElementById('asortyment');
    $("#asortyment option").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });
    $("#asortyment option").filter(function() {
      return $(this).text().toLowerCase().indexOf(value) > -1;
    }).prop('selected', true)
    
    
    
    

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" id="myInput" type="text" placeholder="Search..">

<select autofocus="True" class="form-control  form-select select" id="asortyment" name="asortyment"><option value="493">Berlin</option><option value="494">Warsaw</option><option value="495">New York</option><option value="496">Moscow</option><option value="497">London</option><option value="498">Paris</option><option value="499">Wien</option></select>

Upvotes: 1

Related Questions