简体   繁体   中英

JQuery - Remove all option from Selectbox except for first and selected

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

.not only takes 1 parameter. If you want to filter on two different selectors, you can add a comma between them inside the string. You can also use the :selected selector:

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

See Updated Fiddle: http://jsfiddle.net/znx9hxvu/9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM