6

Re-populate drop down list options, how to clear options list and then re-populate?

When a event fires, I need to wipe out the current contents of the drop down list #users, and then re-populate it via ajax.

My ajax call is returning the HTML for the options like:

<option name=blah1>text1</option>
<option name=blah2>text2</option>
<option name=blah3>text3</option>
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

4 Answers4

24

you can use the below

$('#mySelect').empty()

and then rebind the new data.

kobe
  • 15,671
  • 15
  • 64
  • 91
  • @blankman , #myselect is equivalent to #users. i just gave that code to let you empty the results, yes .html will append the data.. – kobe Nov 09 '10 at 16:40
7

You can just change the html of the select element using the data returned from your ajax call

$("#users").html(data);

so it would look something like this:

$.ajax({
    type: "POST",
    url: url,
    data: data,
    success: : function(data) {
        $("#users").html(data);
    }
    dataType: "HTML"
});
hunter
  • 62,308
  • 19
  • 113
  • 113
2
function(ajaxResult) {
   $('#users').html(""); //clear old options
   $('#users').html(ajaxResult);
}
Gajendra Bang
  • 3,593
  • 1
  • 27
  • 32
0

In the call back of your AJAX call, just clear out the contents of your select element and re-add those returned by the AJAX call.

function(ajaxResult) {
   $('#users').html(ajaxResult);
}
shoebox639
  • 2,312
  • 15
  • 14