2

我想知道是否可以通过 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>
4

3 回答 3

4

请试试这个:

$("#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);

    });
});

您可以在这里看到它的实际效果。

高温高压

于 2010-04-23T17:54:33.573 回答
0

尝试禁用而不是隐藏。

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

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

于 2010-04-23T17:04:28.750 回答
0

没有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>

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

于 2010-04-23T17:42:22.317 回答