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

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



        
相关标签:
12条回答
  • 2020-11-29 19:02

    A much simpler way nowadays is to use the jquery filter() as follows:

    var options = $('select option');
    var query = $('input').val();
    options.filter(function() {
        $(this).toggle($(this).val().toLowerCase().indexOf(query) > -1);
    });  
    
    0 讨论(0)
  • 2020-11-29 19:06

    I had a similar problem to this, so I altered the accepted answer to make a more generic version of the function. I thought I'd leave it here.

    var filterSelectOptions = function($select, callback) {
    
        var options = null,
            dataOptions = $select.data('options');
    
        if (typeof dataOptions === 'undefined') {
            options = [];
            $select.children('option').each(function() {
                var $this = $(this);
                options.push({value: $this.val(), text: $this.text()});
            });
            $select.data('options', options);
        } else {
            options = dataOptions;
        }
    
        $select.empty();
    
        $.each(options, function(i) {
            var option = options[i];
            if(callback(option)) {
                $select.append(
                    $('<option/>').text(option.text).val(option.value)
                );
            }
        });
    };
    
    0 讨论(0)
  • 2020-11-29 19:07

    using Aaron's answer, this can be the short & easiest solution:

    function filterSelectList(selectListId, filterId)
    {
        var filter = $("#" + filterId).val().toUpperCase();
    
        $("#" + selectListId + " option").each(function(i){
           if ($(this).text.toUpperCase().includes(filter))
               $(this).css("display", "block");
           else
               $(this).css("display", "none");
        });
    };
    
    0 讨论(0)
  • 2020-11-29 19:08

    I'm not sure why you have more than one option with the same value, but this works

    $(document).ready(function() {
      $('input').change(function() {
        var filter = $(this).val();
        $('option').each(function() {
          if ($(this).val() == filter) {
            $(this).show();
          } else {
            $(this).hide();
          }
          $('select').val(filter);
        })
      })
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select>
       <option value="something1">something1</option>
       <option value="something1">something1</option>
       <option value="something2">something2</option>
       <option value="something2">something2</option>
       <option value="something2">something2</option>
       <option value="something3">something3</option>
       <option value="something3">something3</option>
       <option value="something3">something3</option>
    </select>
    <input type="text" placeholder="something1">

    0 讨论(0)
  • 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 = $('<option>').text(option.text).val(option.value);
                if (option.attrs) // Add old element options to new entry
                {
                    $.each(option.attrs, function () {
                        $(new_option).attr(this.name, this.value);
                        });
                }
                
                $(select).append(new_option);
            }
          });
        });
      });
    };
    
    0 讨论(0)
  • 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(
                $('<option>').text(option.text)
                .val(option.value)
                .allAttr(option.allAttr)
              );
            }
          });
        });
      });
    };
    
    0 讨论(0)
提交回复
热议问题