JQuery - remove all options from Selectbox except the first and selected

I have an html select box with several options. After selecting an option, I want to select only the selected option and the first option in the drop-down list. I know how to filter and show only one parameter, but I can’t figure out how to enable both options when the “selected” option remains “selected”. I have snippets similar to 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 "on change" function, so I need the selected parameter to remain selected and the rest to be filtered, except for the first. For example, if Oranges were selected, this is what you will see:

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

By the way, I'm using jquery mobile for style.

jsfiddle

+4
1

.not . , . : selected selector:

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

. : http://jsfiddle.net/znx9hxvu/9/

+11

Source: https://habr.com/ru/post/1599124/


All Articles