remove all options from select jquery but only one
55,160
Solution 1
select all options, then exclude the one with that value :
$('#lstCities option[value!="0"]').remove();
Solution 2
Try
$('#lstCities option:lt(-1)').remove()
Demo: Fiddle
Solution 3
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
Related videos on Youtube
Author by
user1428798
Updated on July 09, 2022Comments
-
user1428798 almost 2 years
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>
-
CSS almost 9 yearsThanks 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§ -
jam over 6 yearsI 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.