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

前端 未结 12 588
轮回少年
轮回少年 2020-11-29 18:54



        
12条回答
  •  离开以前
    2020-11-29 19:08

    Just a minor modification to the excellent answer above by Lessan Vaezi. I ran into a situation where I needed to include attributes in my option entries. The original implementation loses any tag attributes. This version of the above answer preserves the option tag attributes:

    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(),
              attrs: this.attributes, // Preserve attributes.
          });
        });
        $(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) { 
                var new_option = $('

提交回复
热议问题