Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear dropdownlist with JQuery

I wrote this little function to fill a drop down list with data from the server.

function fillDropDown(url, dropdown) {     $.ajax({         url: url,         dataType: "json"     }).done(function (data) {         // Clear drop down list         $(dropdown).find("option").remove(); <<<<<< Issue here         // Fill drop down list with new data         $(data).each(function () {             // Create option             var $option = $("<option />");             // Add value and text to option             $option.attr("value", this.value).text(this.text);             // Add option to drop down list             $(dropdown).append($option);         });     }); } 

I can then call the function in this way:

fillDropDown("/someurl/getdata", $("#dropdownbox1")) 

Everything is working perfectly, except for the one line where I'm clearing old data from the drop down list. What am I doing wrong?

Any tips that might help to improve this code are also highly appreciated.

like image 978
Aetherix Avatar asked Mar 28 '12 14:03

Aetherix


People also ask

How do you delete dropdown value?

You can clear the selected item in the below two different ways. By clicking on the clear icon which is shown in DropDownList element, you can clear the selected item in DropDownList through interaction. By using showClearButton property, you can enable the clear icon in DropDownList element.

How remove all options from dropdown in jQuery?

To remove all options from a select list using jQuery, the simplest way is to use the empty() method.

How do you clear the selection in HTML?

To remove the options of an HTML element of select , you can utilize the remove() method: function removeOptions(selectElement) { var i, L = selectElement.


2 Answers

Just use .empty():

// snip... }).done(function (data) {     // Clear drop down list     $(dropdown).empty(); // <<<<<< No more issue here     // Fill drop down list with new data     $(data).each(function () {         // snip... 

There's also a more concise way to build up the options:

// snip... $(data).each(function () {     $("<option />", {         val: this.value,         text: this.text     }).appendTo(dropdown); }); 
like image 145
Matt Ball Avatar answered Oct 27 '22 02:10

Matt Ball


I tried both .empty() as well as .remove() for my dropdown and both were slow. Since I had almost 4,000 options there.

I used .html("") which is much faster in my condition.
Which is below

  $(dropdown).html(""); 
like image 29
शेखर Avatar answered Oct 27 '22 02:10

शेखर