remove all options from select jquery but only one
Asked Answered
A

5

14

I have a select that contain this values:

<select id="lstCities" class="valid" name="City">
<option value="OSNY">OSNY</option>
<option value="dd">dd</option>
<option value="OSffNY">OSffNY</option>
<option value="ANTONY">ANTONY</option>
<option value="0">Autre...</option>
</select>

How can I delete all options but i would like to keep only

 <option value="0">Autre...</option>

My problem is my list is dynamic sometimes I have 3,5,7,.... select + the last one <option value="0">Autre...</option>

Abiosis answered 18/9, 2013 at 7:56 Comment(1)
Thank you so much for asking this question. I wasted 2 days trying to deal with multiple dynamic select boxes that for some stupid reason when they designed selects they didn't add a read-only option.Biscay
U
43

select all options, then exclude the one with that value :

$('#lstCities option[value!="0"]').remove();

FIDDLE

Unruffled answered 18/9, 2013 at 8:0 Comment(1)
Thanks for that. My need of this code deals more with excluding a file from a concatenation and minification process headed by stream.pipe, but it still showed me what I needed to exclude it: $('script[src!="variables.json"]').remove(); Thanks a bunch! -C§Mackoff
R
8

Try

$('#lstCities option:lt(-1)').remove()

Demo: Fiddle

Rounders answered 18/9, 2013 at 7:58 Comment(0)
C
4
$('#lstCities option[value!=0]').remove()

You should remove by value and not rely on the position of the option element to keep.

Chavis answered 18/9, 2013 at 8:1 Comment(0)
B
2

If the option is always the last one, I hope this JavaScript code can help you:

var lastNode = $("#lstCities option").last();
var option = { value:lastNode.val(), text:lastNode.text() };

$('#lstCities').find('option').remove().end().append($('<option>',{
        value:option.value,
        text:option.text,
}));

Learned from this post

Booby answered 18/9, 2013 at 9:24 Comment(0)
A
0

This worked for me:

$("#selectList option").remove();
Audio answered 17/10, 2017 at 3:7 Comment(1)
I apologize for posting code that doesn't pertain to this post. My code is for removing all items in a select list. If you want to keep one, refer to the above suggestions. Make note that options are just like arrays or the index of a string - the value begins at 0.Audio

© 2022 - 2024 — McMap. All rights reserved.