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>

user1428798
  • 1,534
  • 3
  • 24
  • 50
  • 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. – chris loughnane Dec 15 '17 at 10:32

5 Answers5

43

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

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

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 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§ – CSS Sep 01 '15 at 16:12
8

Try

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

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
4
$('#lstCities option[value!=0]').remove()

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

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

Community
  • 1
  • 1
Cedric
  • 95
  • 2
  • 9
0

This worked for me:

$("#selectList option").remove();
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
jam
  • 1
  • 2
  • 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. – jam Oct 18 '17 at 04:37