简体   繁体   English

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

[英]How to remove and replace select options using jquery?

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.我所做的是我有 2 个选择框。 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>

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/ http://api.jquery.com/empty/

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.注意:不要在循环中调用 append 方法并缓存选择器。

this is the native java-script correct working form:这是本机 java 脚本正确的工作形式:

// 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工作小提琴示例

You should clear the cities div before appending to it like this:在像这样附加到它之前,您应该清除城市 div:

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

}

Before for loop,add this code.在 for 循环之前,添加此代码。

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

Working Fiddle工作小提琴

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

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.仅仅因为我遇到了这种情况——我想我会提到,如果你使用 bootstrap-select 来美化你的选择框(或者甚至是另一个类似的 javascript 视觉替代传统的 html 选择),你可能需要在你一次刷新它我重新填充了选项。 In the case of select-bootstrap it's a matter of $(element).selectpicker('refresh') - in example:在 select-bootstrap 的情况下,它是$(element).selectpicker('refresh') - 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM