Alex Rivera | Logout

How to dynamic filter options of <select > with jQuery?

Asked 2009-09-19T04:22:21.863
52
<select >
<option value="something">something</option>
<option value="something_else">something else</option>
</select>
<input type="text" >

So that when user inputs something, only options with value matching the input will show.

Edit
Report

1 Answer

21

I'm not sure why you have more than one option with the same value, but this works

$(document).ready(function() {
  $('input').change(function() {
    var filter = $(this).val();
    $('option').each(function() {
      if ($(this).val() == filter) {
        $(this).show();
      } else {
        $(this).hide();
      }
      $('select').val(filter);
    })
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
   <option value="something1">something1</option>
   <option value="something1">something1</option>
   <option value="something2">something2</option>
   <option value="something2">something2</option>
   <option value="something2">something2</option>
   <option value="something3">something3</option>
   <option value="something3">something3</option>
   <option value="something3">something3</option>
</select>
<input type="text" placeholder="something1">

answered 2009-09-19T07:49:15.613

Your Answer