TotalNewbie
TotalNewbie

Reputation: 1024

How to remove all options from a dropdown using jQuery / JavaScript

I have a dropdown as seen below:

<select id="models" onchange="removeElements()">
            <option id = "remove" value="0">R8</option>
            <option id = "remove" value="1">Quattro</option>
            <option id = "remove" value="2">A6 hatchback</option>
</select>

How would I create the script removeElements() that would remove all of the options within the select?

Upvotes: 27

Views: 122456

Answers (7)

Piotr
Piotr

Reputation: 1947

Other approach for Vanilla JavaScript:

for(var o of document.querySelectorAll('#models > option')) {
  o.remove()
}

Upvotes: 0

user3506285
user3506285

Reputation: 86

Anyone using JavaScript (as opposed to JQuery), might like to try this solution, where 'models' is the ID of the select field containing the list :-

var DDlist = document.getElementById("models");
while(DDlist.length>0){DDlist.remove(0);}

Upvotes: 1

Mir Gulam Sarwar
Mir Gulam Sarwar

Reputation: 2648

You didn't say on which event.Just use below on your event listener.Or in your page load

$('#models').empty()

Then to repopulate

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

Upvotes: 81

Jesse
Jesse

Reputation: 65

In case .empty() doesn't work for you, which is for me

function SetDropDownToEmpty() 
{           
$('#dropdown').find('option').remove().end().append('<option value="0"></option>');
$("#dropdown").trigger("liszt:updated");          
}

$(document).ready(
SetDropDownToEmpty() ;
)

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82251

You can either use .remove() on option elements:

.remove() : Remove the set of matched elements from the DOM.

 $('#models option').remove(); or $('#models').remove('option');

or use .empty() on select:

.empty() : Remove all child nodes of the set of matched elements from the DOM.

 $('#models').empty();

however to repopulate deleted options, you need to store the option while deleting.

You can also achieve the same using show/hide:

$("#models option").hide();

and later on to show them:

$("#models option").show();

Upvotes: 13

Dhambha
Dhambha

Reputation: 82

Try this

function removeElements(){
    $('#models').html("");
}

Upvotes: 0

Deepu--Java
Deepu--Java

Reputation: 3840

function removeElements(){
  $('#models').html('');
}

Upvotes: 0

Related Questions