jquery选择选项删除初始选项并替换为其他选项
下面是jquery,它通过ajax向select输入添加了新选项。然而,select最初有一个选项,我想删除它,然后用通过ajax返回的选项替换它jquery选择选项删除初始选项并替换为其他选项,jquery,ajax,Jquery,Ajax,下面是jquery,它通过ajax向select输入添加了新选项。然而,select最初有一个选项,我想删除它,然后用通过ajax返回的选项替换它 $(document).ready(function () { $('#id_previous_postcode').change(function () { var postcode = $(this).val() console.log(postcode) $.ajax({ // could prevent
$(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时,您可以选择
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);
});
}
我建议使用
$("SELECTOR").first().detach();
然后
$("NEW ELEMENT").preppendTo($("SELECTOR").first().parent());
您能在触发jQuery之前发布选择器的外观吗?