Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to "live search" (filter) items on a HTML select

How do I use jQuery to "live search" or filter items on a HTML select drop down list?

I have a simple text input and a select (multiple).

I want to filter items from that select according to input..

like image 508
Vitor Reis Avatar asked Sep 16 '10 19:09

Vitor Reis


1 Answers

Just the relevant parts of my attempt (visible at http://jsfiddle.net/VeLKW/2/):

<script type="text/javascript">
$(function() {
  var opts = $('#optlist option').map(function(){
    return [[this.value, $(this).text()]];
  });

  $('#someinput').keyup(function(){
    var rxp = new RegExp($('#someinput').val(), 'i');
    var optlist = $('#optlist').empty();
    opts.each(function(){
      if (rxp.test(this[1])) {
        optlist.append($('<option/>').attr('value', this[0]).text(this[1]));
      }
    });
  });
});
</script>

<input id="someinput"><br><select id="optlist" multiple="multiple">
<option value="1">foo</option>
<option value="2">bar</option>
<option value="3">foobar</option>
<option value="4">foobarbaz</option>
</select>
like image 125
DMI Avatar answered Sep 25 '22 13:09

DMI