user311509
user311509

Reputation: 2866

Clear Options and Re-Populate the Dropdown List - jQuery/Ajax

Question: How to clear options list and then re-populate?

Description: When a event fires, I need to wipe out the current contents of the drop down list of #regionlist and #citylist.

Problem: once user submits the form via GET method. Region list and city list values get accumulated (new cities + the previous list of cities (before refresh)).

The code below populates the lists, how can i clear the list before populating the list

function getRegions(e){//search regions from databse using ajax and jquery
    if(e!=''){
        $.post("library/region.php", {ids: e },
           function(data){
            $("#regionlist").html(data.regions); 
           if(data.cities){//if region not exists show the cities 
             $("#citylist").html(data.cities);
            } 
        }, "json");
    }   
}
function getCities(e){//search cities from databse using ajax and jquery
    if(e!=''){
        $.post("library/city.php", {ids: e },
       function(data){
         $("#citylist").html(data);
       });
    }
}

Upvotes: 4

Views: 13375

Answers (2)

talha2k
talha2k

Reputation: 25650

Try this:

$('#regionlist')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever"></option>')
    .val('whatever');

$('#citylist')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever"></option>')
    .val('whatever');

Hope this helps.

Upvotes: 7

Shagglez
Shagglez

Reputation: 1522

$('select').find('option').remove();

or if you have option groups as well, you can use the same method you use to populate them, $('select').html('');

Upvotes: 3

Related Questions