简体   繁体   English

如何使用 jQuery 搜索 optgroup label

[英]How can I search optgroup label with jQuery

I have a list with the states of the United States in a select and I need filter by the optgroup label.我在 select 中有美国各州的列表,我需要按 optgroup label 过滤。

For example: If I search for Alabama, I need to return to another select with Birmingham and Huntsville例如:如果我搜索阿拉巴马州,我需要返回另一个 select 与伯明翰亨茨维尔

I'm using this jQuery code and this code works when I search by options, but I need search by groups.我正在使用这个 jQuery 代码,当我按选项搜索时,此代码有效,但我需要按组搜索。

How can I change the jQuery to return only the cities of the states in which I search ?如何更改 jQuery 以仅返回我搜索的州的城市

Here is my working code: https://jsfiddle.net/km7s9er5/这是我的工作代码: https://jsfiddle.net/km7s9er5/

Thanks in advance for someone helping me with this在此先感谢有人帮助我

 $(document).ready(function() { jQuery.fn.filterByText = function(textbox, selectSingleMatch) { return this.each(function() { var select = this; var options = []; $('#myfiltercities_id').hide(); $(select).find('option').each(function() { options.push({ value: $(this).val(), text: $(this).text() }); }); $(select).data('options', options); $(textbox).bind('change keyup', function() { $('#myfiltercities_id').hide(); var options = $(select).empty().data('options'); var search = $(this).val().trim(); 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) ); } }). if (selectSingleMatch === true && $(select).children().length === 1) { $(select).children().get(0);selected = true; } }); }); }. $(function() { $('#myfiltercities_id'),filterByText($('#textbox'); true). $("select option");click(function() { alert(1); }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> <select name="myfiltercities" id="myfiltercities_id"> <option value=""></option> <optgroup label="AL"></optgroup> <optgroup label="Alabama"> <option value="123">Birmingham</option> <option value="123">Huntsville</option> </optgroup> <optgroup label="AK"></optgroup> <optgroup label="Alaska"> <option value="456">Anchorage</option> <option value="789">Juneau</option> <option value="135">Fairbanks</option> </optgroup> <optgroup label="AZ"></optgroup> <optgroup label="Arizona"> <option value="198">Phoenix</option> <option value="065">Tucson</option> </optgroup> <optgroup label="AR"></optgroup> <optgroup label="Arkansas"> <option value="835">Little Rock</option> </optgroup> <optgroup label="CA"></optgroup> <optgroup label="California"> <option value="402">Los Angeles</option> </optgroup> </select>

Consider the following code.考虑以下代码。

https://jsfiddle.net/Twisty/zvtymk1r/29/ https://jsfiddle.net/Twisty/zvtymk1r/29/

HTML HTML

<form action="/action_page.php">
  <label for="fname">Find City</label>
  <input type="text" id="textbox" name="textbox"><br><br>

  <select name="myfiltercities" id="myfiltercities_id">
    <option value=""></option>
    <optgroup label="Alabama" data-abbr="AL">
      <option value="123">Birmingham</option>
      <option value="123">Huntsville</option>
    </optgroup>
    <optgroup label="Alaska" data-abbr="AK">
      <option value="456">Anchorage</option>
      <option value="789">Juneau</option>
      <option value="135">Fairbanks</option>
    </optgroup>
    <optgroup label="Arizona" data-abbr="AZ">
      <option value="198">Phoenix</option>
      <option value="065">Tucson</option>
    </optgroup>
    <optgroup label="Arkansas" data-abbr="AR">
      <option value="835">Little Rock</option>
    </optgroup>
    <optgroup label="California" data-abbr="CA">
      <option value="402">Los Angeles</option>
    </optgroup>
  </select>
</form>

JavaScript JavaScript

jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
  return this.each(function() {
    var select = this;
    $('#myfiltercities_id').hide().children().hide();
    $(textbox).on("change keyup", function(e) {
      $('#myfiltercities_id').hide().children().hide();
      var search = $(this).val().trim().toLowerCase();
      if (search.length >= 2) {
        $('#myfiltercities_id').show();
        $("optgroup", select).each(function(i, el) {
          var label = $(el).attr("label").toLowerCase();
          var abbr = $(el).data("abbr").toLowerCase();
          if (search.length == 2) {
            if (abbr == search) {
              console.log(search, label, abbr);
              $(el).show();
            }
          } else {
            if (label.indexOf(search) >= 0) {
              console.log(search, label, abbr);
              $(el).show();
            }
          }
        });
      }
    });
  });
}

$(function() {
  $('#myfiltercities_id').filterByText($('#textbox'), true);
  $("select option").click(function() {
    alert(this.value);
  });
});

First your HTML Structure was not conducive to a proper search.首先,您的 HTML 结构不利于正确搜索。 The abbreviation had no correlation with the results.缩写与结果无关。 I moved this to a Data attribute associated with the cities.我将其移至与城市关联的数据属性。

Your search feature was originally designed for Option elements and not good for groups.您的搜索功能最初是为选项元素设计的,不适合组。 Also it was re-adding Options back to the select.它还将选项重新添加回 select。 It seemed overly complex.它似乎过于复杂。

I find it easier, when filtering, to simply Hide all items and then Show items that match the filter.我发现在过滤时,简单地隐藏所有项目然后显示与过滤器匹配的项目更容易。 based on the number of characters in the input, we might be searching for an abbreviation or a full state name.根据输入中的字符数,我们可能正在搜索缩写词或完整的 state 名称。 This is an easy condition to look at.这是一个容易查看的条件。

So if the User searches for "al" , they will get Alabama, but if they then continue to "ala" , they will Alabama and Alaska.因此,如果用户搜索"al" ,他们将获得阿拉巴马州,但如果他们继续搜索"ala" ,他们将获得阿拉巴马州和阿拉斯加州。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM