如何使用jquery删除和替换选择选项?

问题描述:

这里需要一些帮助。我有一个动态表单,使用户可以选择他/她正确的地址。我做的是我有2个选择框。一个是国家,第二个是城市。在用户选择他/她的状态之后,下拉城市选项将根据所选状态动态地改变。我的问题是,我正在追加它。这就是我改变正确城市的问题。因为它将显示先前选择的选项值。它不断追加和追加。知道我该如何解决这个问题?这是我的代码。

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

以下是城市选择:

<select id="city" name="city">
    <option value="">---Select City---</option>
</select>


删除所有选项并再次附加默认选项:

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/