Clear dropdownlist with JQuery

JavascriptJquery

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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);
});

Solution 2 - Javascript

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("");

Solution 3 - Javascript

<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>
   

Solution 4 - Javascript

How about storing the new options in a variable, and then using .html(variable) to replace the data in the container?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAetherixView Question on Stackoverflow
Solution 1 - JavascriptMatt BallView Answer on Stackoverflow
Solution 2 - JavascriptशेखरView Answer on Stackoverflow
Solution 3 - JavascriptGurungView Answer on Stackoverflow
Solution 4 - JavascriptRobertView Answer on Stackoverflow