28

Need a little help here. I have a dynamic form that enables user to select his/her correct addresses. What I did is I have 2 select boxes. One is States and second is city. After the user choose his/her states the dropdown city options will be change dynamically according to the selected states. My problem is, I am appending it. That's why I have a problem changing the correct city. Because it will display the previous selected option value. It keeps on appending and appending. Any idea how can I work on this? Here's my code.

$('#state').on('change',function(){    
    var state_code = $('#state').val();    
    var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';    
    $.ajax({    
        type: 'POST',
        url: city_url,
        data: '',
        dataType: 'json',
        async: false,
        success: function(i){    
            var select = $('#city');    
            for (var j = 0; j < i.length; j++){                 
                console.log(i[j].name + "--" + i[j].id);
                $("#city").append("<option value='" +i[j].name+ "'>" +i[j].name+ "</option>");    
            }    
        }    
    });    
});

Here's the select for city:

<select id="city" name="city">
    <option value="">---Select City---</option>
</select>
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
Jerielle
  • 7,144
  • 29
  • 98
  • 164

7 Answers7

62

Removes all options and appends your default one again:

var select = $('#city');
select.empty().append('<option value="">---Select City---</option>');

http://api.jquery.com/empty/

Enam
  • 1,268
  • 1
  • 9
  • 16
  • Ok thanks. It is now working but how can I skip the remove in the first option? So every city the first option is always empty? – Jerielle Nov 27 '13 at 07:52
  • `$('#city option:gt(0)').remove();` avoids deleting the first option so you don't have to re-add it. – AntonChanning Dec 12 '16 at 11:15
5

You can do the following:

var selectbox = $('#city');
selectbox.empty();
var list = '';
for (var j = 0; j < i.length; j++){
        list += "<option value='" +i[j].name+ "'>" +i[j].name+ "</option>";
}
selectbox.html(list);

Note: Don't call the append method in the loop and also cache the selectors.

Ramesh
  • 4,223
  • 2
  • 16
  • 24
5

this is the native JavaScript correct working form:

// get the select html element by id
var selectElement = document.getElementById('city');

// remove all options from select
selectElement.options.length = 0;

// create new option element
var newOptionElement = document.createElement('option');
newOptionElement.value = "optionValue";
newOptionElement.innerHTML = "option display text";

// add the new option into the select
selectElement.appendChild(newOptionElement);

Working Fiddle example

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Shaybc
  • 2,628
  • 29
  • 43
3

You should clear the cities div before appending to it like this:

success: function(i){

    var select = $('#city');

    select.empty();

    select.append("<option value=''>---Select City---</option>");

    for (var j = 0; j < i.length; j++){
            console.log(i[j].name + "--" + i[j].id);
            $("#city").append("<option value='" +i[j].name+ "'>" +i[j].name+ "     </option>");
    }

}
Bart Beyers
  • 3,386
  • 1
  • 20
  • 20
2

Before for loop,add this code.

$("#city option").each(function() {
$(this).remove();
});

Working Fiddle

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
2

Try it like,

 success: function(i){
    var select = $('#city');
    // remove previous data and add default option
    select.html('<option value="">---Select City---</option>');
    for (var j = 0; j < i.length; j++){
       console.log(i[j].name + "--" + i[j].id);
       select.append("<option value='" +i[j].name+ "'>" +i[j].name+ "</option>");
    }
}
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Simply because I ran into this situation - I thought I'd mention that if you are using bootstrap-select to prettify your select boxes (or even another similar javascript visual substitution for your conventional html select) you may need to refresh it once you've repopulated the options. In the case of select-bootstrap it's a matter of $(element).selectpicker('refresh') - in example:

function changeSelectOptions( id, max ) {
    var selectbox = $(id);
    selectbox.empty();
    var list = '';
    for (var j = 1; j < max; j++){
        list += "<option value='" +j+ "'>" +j+ "</option>";
    }
    selectbox.html(list);
    $(id).selectpicker('refresh');
}
Grant
  • 5,709
  • 2
  • 38
  • 50