我有下面的jquery,它通过ajax为select输入添加了新选项。然而,select最初有一个选项,我想删除,然后替换为通过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);
});
}
})
})
})
答案 0 :(得分:2)
当您使用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);
});
}
答案 1 :(得分:0)
我建议使用
$("SELECTOR").first().detach();
然后......
$("NEW ELEMENT").preppendTo($("SELECTOR").first().parent());