我在填充选择框选项时遇到问题,取决于之前的选择框
问题是每当我从第一个选择框中选择值(即#city)时,它给出了城市值的结果,这很好但是只要我选择第二个值,它就会给出第二个值的结果以及第一个价值观。
下面是我的代码
HTML CODE
<lable>City</lable>
<select id="city" style="width:100%;text-align:left;" onchange="getSchool()"></select>
<span id='paymentform_city_errorloc' class='error'></span>
<br>
<br>
<lable>School</lable>
<select id="school" style="width:100%;">
</select>
<span id='paymentform_school_errorloc' class='error'></span>
<br>
<br>
JS CODE
var cityname, city, schoolname, schooldata, cityid, city1;
var cityarray = [];
var schoolarray = [];
function getCity() {
jQuery.ajax({
url: baseurl + "getcity.php",
async: true
, success: function (data) {
data = $.trim(data);
if (data == "false") {
console.log(data);
} else {
var myArray = jQuery.parseJSON(data);
jQuery(myArray).each(function (index, element) {
cityname = element.cityname;
cityid = element.city_id;
cityarray.push([cityname, cityid])
});
for (var i = 0; i < cityarray.length; i++) {
city1 += '<option value="' + cityarray[i][1] + '">' + cityarray[i][0] + '</option>';
}
$('#city').html("<option disabled selected></option>" + city1);
}
}
});
}
function getSchool() {
var city_id = $('#city').val();
jQuery.ajax({
url: baseurl + "getschool.php"
, data: 'cityid=' + city_id
, type: "POST"
, success: function (response) {
response = $.trim(response);
if (response == "false") {
$('#school').prop('disabled', 'disabled');
} else {
$('#school').prop('disabled', false);
console.log(response);
$('#school').append(response);
}
}
, error: function () {}
});
}
答案 0 :(得分:1)
function getSchool() {
var city_id = $('#city').val();
schoolarray = []; //Add this code.
进行上述更改。每次选择新城市时,您的学校阵列都会重置。