bos570
bos570

Reputation: 1523

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

Upvotes: 8

Views: 15002

Answers (1)

Stryner
Stryner

Reputation: 7318

.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/

Upvotes: 22

Related Questions