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

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



        
12条回答
  •  情话喂你
    2020-11-29 19:09

    Update Lessan's answer to also keep the attributes of the options.

    This is my first time answering on Stack Overflow so not sure if I should edit his answer or create my own.

    jQuery.fn.allAttr = function() {
      var a, aLength, attributes, map;
      if (!this[0]) return null;
      if (arguments.length === 0) {
        map = {};
        attributes = this[0].attributes;
        aLength = attributes.length;
        for (a = 0; a < aLength; a++) {
          map[attributes[a].name.toLowerCase()] = attributes[a].value;
        }
        return map;
      } else {
        for (var propin arguments[0]) {
          $(this[0]).attr(prop, arguments[0][prop]);
        }
        return this[0];
      }
    };
    
    
    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(), 
            allAttr: $(this).allAttr() });
        });
        $(select).data('options', options);
    
        $(textbox).bind('change keyup', function() {
          var search = $.trim($(this).val());
          var regex = new RegExp(search, "gi");
    
          $.each($(select).empty().data('options'), function(i, option) {
            if (option.text.match(regex) !== null) {
              $(select).append(
                $('

提交回复
热议问题