我有下面的 jquery 片段,它通过 ajax 向选择输入添加新选项。然而,选择最初有一个选项,我想删除它,然后替换为通过 ajax 返回的选项。
$(document).ready(function () {
$('#id_previous_postcode').change(function () {
var postcode = $(this).val()
console.log(postcode)
$.ajax({
// could prevent url hard coding by using url tag in form widget attribute and assign url key here to that attr
url: '/users/prior_addresses_ajax/',
data: {
'postcode': postcode
},
dataType: 'json',
success: function (data) {
var select = document.querySelector('#id_previous_full_address');
console.log(data)
data.property_choices.forEach(function (subarray) {
var option = new Option(subarray[1], subarray[0]);
select.options.add(option);
});
}
})
})
})
最佳答案
当您使用 jQuery 时,您可以 .empty()
选择。
success: function (data) {
// Will remove previous set options from select
$('#id_previous_full_address').empty();
var select = document.querySelector('#id_previous_full_address');
console.log(data)
data.property_choices.forEach(function (subarray) {
var option = new Option(subarray[1], subarray[0]);
select.options.add(option);
});
}
关于jquery select options 删除初始选项并替换为其他选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46836005/