JQuery - 移除选择框中除第一个和已选项外的所有选项。

8

I have a html select box with several options. Upon selection of an option I want Only the selected option and the first option to be shown in the select option dropdown. I know how to filter and show only one option but I cannot figure out how to include both option where the 'selected' option remains 'selected'. I have include snippets similar to of my code as well as a demo.

HTML:

<select id="myDropdown">
<option selected>Select fruit</option>
<option>Grapes</option>
<option>Bananas</option>
<option>Oranges</option>
<option>Apples</option>
</select>

JS:

$(document).on('change', '#myDropdown', function() {
    $('option', this).not(this,'option:gt(0)').siblings().remove(); });

I am trying to use the first option to perform another function 'on change' so I need the selected option to remain selected while the rest being filtered out except for the first. For example if 'Oranges' were selected, this is what you would see:

<select id="myDropdown">
     <option>Select fruit</option>
     <option>Oranges</option>  //selcted value
</select>

BTW I am using jquery mobile to style as well.

jsfiddle

1个回答

22

.not 只接受1个参数。如果您想在两个不同的选择器上过滤,可以在字符串内部它们之间添加逗号。您也可以使用:selected 选择器:

$('option', this).not(':eq(0), :selected').remove();

查看更新后的代码片段:http://jsfiddle.net/znx9hxvu/9/


完美运行!谢谢。 - bos570

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接