Mou
Mou

Reputation: 16282

How to remove all entry from dropdown except first one

My dropdown html say look like this

<select id="models" ">
    <option id = "remove" value="">--Select--</option>
    <option id = "remove" value="0">R8</option>
    <option id = "remove" value="1">Quattro</option>
    <option id = "remove" value="2">A6 hatchback</option>
</select>

i know how to remove all entry from dropdown and add new data again as per below code.

$.getJSON('@Url.Action("YourUrl")',function(data){

     var dropdown=$('#models');
    dropdown.empty();  
    $.each(data, function (index, item) {
        dropdown.append(
            $('<option>', {
                value: item.valueField,
                text: item.DisplayField
            }, '</option>'))
          }
         )});

but i like to know how to keep this row <option id = "remove" value="">--Select--</option> when removing all other item from dropdown ?

thanks

Upvotes: 1

Views: 6450

Answers (3)

guest271314
guest271314

Reputation: 1

Try using :gt() selector with parameter 0, substituting className "remove" for duplicate ids "remove" at option elements

$("#models option:gt(0)").remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<select id="models">
            <option class="remove" value="">--Select--</option>
            <option class="remove" value="0">R8</option>
            <option class="remove" value="1">Quattro</option>
            <option class="remove" value="2">A6 hatchback</option>
</select>

Upvotes: 1

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

You can filter out the item with value of empty string with a selector:

$("#models option:not([value=''])").remove();

This ensures that all other options will be removed regardless of which index your empty value option is positioned at.

Upvotes: 3

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

First, do not duplicate id values (this causes JavaScript to get confused), but you can do so with classes. Secondly, you can just use:

$("option:not(:first)").remove();

Also note, you are not closing the tag correctly:

<select id="models" ">
<!------------------^ remove this

Snippet

$(function () {
  $("#models").find("option:not(:first)").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="models">
  <option value="">--Select--</option>
  <option value="0">R8</option>
  <option value="1">Quattro</option>
  <option value="2">A6 hatchback</option>
</select>

Upvotes: 8

Related Questions