Clear dropdown with jQuery

I wrote this little function to populate the 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); }); }); } 

Then I can call the function as follows:

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

Everything works fine except for one line where I clear old data from a drop down list. What am I doing wrong?

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

+53
javascript jquery
Mar 28 2018-12-12T00:
source share
4 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 create options:

 // snip... $(data).each(function () { $("<option />", { val: this.value, text: this.text }).appendTo(dropdown); }); 
+154
Mar 28 2018-12-12T00:
source share

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

I used .html("") , which is much faster in my state.
What's below

  $(dropdown).html(""); 
+15
Nov 16 '13 at 10:57
source share

How to save new options in variable and then using .html(variable) replace data in container ?

0
Mar 28 2018-12-12T00:
source share
 <select id="ddlvalue" name="ddlvaluename"> <option value='0' disabled selected>Select Value</option> <option value='1' >Value 1</option> <option value='2' >Value 2</option> </select> <input type="submit" id="btn_submit" value="click me"/> <script> $('#btn_submit').on('click',function(){ $('#ddlvalue').val(0); }); </script> 
0
Mar 03 '16 at 5:01
source share



All Articles