通过输入框和jquery筛选选择列表
我想知道是否可以通过jquery获得一些帮助,使用输入框过滤选择列表 下面是我的js看起来的样子,但它似乎不起作用。 我猜这是因为选择列表中的选项不可隐藏通过输入框和jquery筛选选择列表,jquery,filtering,selectlist,Jquery,Filtering,Selectlist,我想知道是否可以通过jquery获得一些帮助,使用输入框过滤选择列表 下面是我的js看起来的样子,但它似乎不起作用。 我猜这是因为选择列表中的选项不可隐藏 <script type="text/javascript"> $(document).ready(function() { $("#inputFilter").change(function() { var filter = $(this).val();
<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>
尝试禁用而不是隐藏
$(this).attr('disabled', 'disabled');
您可以做的另一件事是从DOM中完全删除该选项。没有文本属性
试着这样做:
<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>
编辑:编辑了我的答案,因为我误读了一些内容。请尝试以下操作:
$("#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);
});
});
你可以在行动中看到它
HTH如何从dom中删除它。我可能还需要在某个地方保留原始选择列表的克隆,对吗?