Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 884
TotalNewbie Avatar asked Apr 10 '14 12:04

TotalNewbie


People also ask

How do you remove all options from select in jQuery except first?

Explanation: If we want to remove all items from dropdown except the first item then we can use $('#ddlItems option:not(:first)'). remove(); Here we have excluded first item from being deleted. If we want to remove all items from dropdown except the last item then we can use $('#ddlItems option:not(:last)').

How do you reset a drop down?

The following HTML Markup consists of an HTML DropDownList (DropDown) control and a Button. When the Button is clicked, the Reset JavaScript function is executed. Inside this function, the SelectedIndex property of the DropDownList is set to 0 (First Item).


1 Answers

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>'))       }      )}); 
like image 147
Mir Gulam Sarwar Avatar answered Sep 21 '22 02:09

Mir Gulam Sarwar