How to dynamic filter options of with jQuery?

Example 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">

Live demo here:
http://www.lessanvaezi.com/filter-select-list-options/

Leave a Comment