开发者

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

开发者 https://www.devze.com 2023-01-16 23:24 出处:网络
开发者_运维问答How do I use jQuery to \"live search\" or filter items on a HTML select drop down list?
开发者_运维问答

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


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

精彩评论

暂无评论...
验证码 换一张
取 消