2010-04-23 64 views
2

我想知道如果我可以得到一些幫助,通過jQuery使用輸入框過濾選擇列表。通過輸入框和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

請試試這個:

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

+0

這不起作用,並且該示例已損壞 – 2012-12-05 16:50:16

0

嘗試禁用的,而不是隱藏。

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

你可以做的另一件事是從DOM中刪除選項。

+0

我將如何去從dom中刪除它。 我可能還需要保留原始選擇列表的克隆,以及對嗎? – zSynopsis 2010-04-23 17:22:49

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> 

編輯:編輯我的答案,因爲我誤解出頭。