<select >
<option value="something">something</option>
<option value="something_else">something else</option>
</select>
<input type="text" >

这样,当用户输入某些内容时,只会显示与输入值匹配的选项。

最佳答案

HTML示例:

//jQuery extension method:
jQuery.fn.filterByText = function(textbox) {
  return this.each(function() {
    var select = this;
    var options = [];
    $(select).find('option').each(function() {
      options.push({
        value: $(this).val(),
        text: $(this).text()
      });
    });
    $(select).data('options', options);

    $(textbox).bind('change keyup', function() {
      var options = $(select).empty().data('options');
      var search = $.trim($(this).val());
      var regex = new RegExp(search, "gi");

      $.each(options, function(i) {
        var option = options[i];
        if (option.text.match(regex) !== null) {
          $(select).append(
            $('<option>').text(option.text).val(option.value)
          );
        }
      });
    });
  });
};

// You could use it like this:

$(function() {
  $('select').filterByText($('input'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="hello">hello</option>
  <option value="world">world</option>
  <option value="lorem">lorem</option>
  <option value="ipsum">ipsum</option>
  <option value="lorem ipsum">lorem ipsum</option>
</select>
<input type="text">


现场演示在这里:
http://www.lessanvaezi.com/filter-select-list-options/

07-24 20:47