【问题标题】:Filtering a select list via input box & jquery通过输入框和 jquery 过滤选择列表
【发布时间】:2011-02-11 14:57:03
【问题描述】:

我想知道是否可以通过 jquery 使用输入框过滤选择列表。

这是我的 js 的样子,但它似乎不起作用。 我猜这是因为选择列表中的选项是不可隐藏的。

    <script type="text/javascript">
    $(document).ready(function() {
        $("#inputFilter").change(function() {
            var filter = $(this).val();

            $("#selectList option").each(function() {
                var match = $(this).text().search(new RegExp(filter, "i"));
                if (match > 0) {
                    $(this).show(); // Does not work
                }
                else
                    $(this).hide();
            });
        });
    });
</script>

这是我的html

<input id="inputFilter" />
<select id="selectList">
    <option value="1111" >1111 - London</option>
    <option value="1112" >1112 - Paris </option>
</select>

【问题讨论】:

    标签: jquery filtering selectlist


    【解决方案1】:

    没有text 属性。

    试试这样的:

    <input id="inputFilter" />
    <select id="selectList">
       <option value="1111">1111 - London</option>
       <option value="1112">1111 - Paris</option>
    </select>
    
    <script>
    $(document).ready(function() {
       $("#inputFilter").change(function() {
          var filter = $(this).val();
          $("#selectList option").each(function() {
             var match = $(this).text().search(new RegExp(filter, 'i'));
    
             if (match > 0) {
                $(this).show();
             }
             else{
                $(this).hide();
             }
          });
       });
    });
    </script>
    

    编辑:编辑了我的答案,因为我误读了一些内容。

    【讨论】:

      【解决方案2】:

      请试试这个:

      $("#inputFilter").change(function() {
          var filter = $(this).val();
          //alert(filter);
          $("#selectList option").each(function() {
              var match = $(this).text().search(new RegExp(filter, "i"));
              //alert(match);
              if (match < 0 && $(this).text() != "--select--")  {                   
                  $(this).attr("disabled",true);
              }
              else
                  $(this).attr("disabled",false);
      
          });
      });
      

      你可以在here看到它。

      HTH

      【讨论】:

        【解决方案3】:

        尝试禁用而不是隐藏。

        $(this).attr('disabled', 'disabled');
        

        您可以做的另一件事是从 DOM 中完全删除该选项。

        【讨论】:

        • 我将如何从 dom 中删除它。我可能还需要在某处保留原始选择列表的克隆,对吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-13
        • 2017-09-09
        • 2017-04-23
        • 2012-08-20
        • 2019-03-22
        • 1970-01-01
        • 2012-11-09
        相关资源
        最近更新 更多