【发布时间】:2021-03-17 19:52:28
【问题描述】:
当用户在输入下拉列表中选择数据时,我想更改输入值。在 html 下拉列表中循环和设置数据值后要做的第一件事是检查该选项是否被选中,但我对如何检查它感到困惑,所以我只是通过下拉 id 检查但它没有工作,那么如果选择了如何检查数据输入呢?
这是我第一次返回数据下拉列表的ajax代码:
$.ajax({
url : "{{ url('web/city/getdatacity') }}",
type : "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
},
data : {
province_id:id
},
success : function(data){
var html = '';
var postcode = '';
var i;
if(data.length == 0) {
html += '<option value = ""> City not found!</option>';
} else {
for(i=0; i<data.length; i++) {
html += '<option value = "'+ data[i].city_id +'">' + data[i].city_name +'</option>';
if($('#city_id').is(':selected')) { //here the problem when check if option above selected or not
postcode = data[i].postal_code; //input postal code in var postcode if true
}
}
}
$('.city').html(html);
$('#postalcode').val(postcode); //auto fill postal code value from postcode
})
});
【问题讨论】:
-
这听起来主要是客户端问题,你能做一个虚拟的ajax调用并创建一个这样的小提琴吗? jsfiddle.net/GRMule/WQXXT
-
这里的一些代码应该可以帮助stackoverflow.com/questions/11179406/…
-
嗨,
$('#city_id')是您从 ajax 添加选项的下拉菜单?如果刚刚加载下拉菜单,则默认情况下只会将第一个值设置为选中。我不确定您使用的是哪个下拉菜单。请详细说明