我在修改表单中有级联下拉菜单,目的是在级联下拉菜单保持功能正常的情况下,以编程方式填充下拉列表(来自mysql查询的值)而不是仅单击,选择了第一个下拉菜单,但其他下拉菜单是没有填写/选择。如果有人可以帮助我,那将非常好。
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
var stateSel = document.getElementById("stateSel"),
countySel = document.getElementById("countySel"),
citySel = document.getElementById("citySel");
$(document).ready(function() {
for (var state in stateObject) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
stateSel.onchange = function () {
countySel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var county in stateObject[this.value]) {
countySel.options[countySel.options.length] = new Option(county, county);
}
}
stateSel.onchange(); // reset in case page is reloaded
countySel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var cities = stateObject[stateSel.value][this.value];
for (var i = 0; i < cities.length; i++) {
citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
}
}
});
$( "#testing" ).click(function() {
var mystate = "Oregon",
mycounty = "Jackson",
mycity = "Jacksonville";
$("#stateSel option").filter(function() {return $(this).text() == mystate;}).prop("selected", true);
$("#countySel option").filter(function() {return $(this).text() == mycounty;}).prop("selected", true);
$("#citySel option").filter(function() {return $(this).text() == mycity;}).prop("selected", true);
});
<div class="container">
<div class="row mb-4">
<div class="col-xl-4 col-lg-4 col-md-4">
<select name="stateSel" id="stateSel" class="form-control input-md">
<option value="">Select</option>
</select>
<br />
<select name="countySel" id="countySel" class="form-control input-md">
<option value="">Select</option>
</select>
<br />
<select name="citySel" id="citySel" class="form-control input-md">
<option value="">Select</option>
</select>
</div>
</div>
<button type="button" class="btn btn-sm btn-success" id="testing">Trigger Button</button>
</div>