Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

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);
       });
    }
}
like image 225
user311509 Avatar asked Oct 14 '25 20:10

user311509


2 Answers

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.

like image 198
AlphaMale Avatar answered Oct 17 '25 12:10

AlphaMale


$('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('');

like image 39
Shagglez Avatar answered Oct 17 '25 10:10

Shagglez