Javascript 使用JQuery onChange在mvc中填充dropdownlist
在MVC中创建两个下拉列表。当用户在第一个下拉列表中选择某个内容时,我想重新填充第二个下拉列表 在页面加载时,我填充第二个下拉列表,如下所示:Javascript 使用JQuery onChange在mvc中填充dropdownlist,javascript,jquery,Javascript,Jquery,在MVC中创建两个下拉列表。当用户在第一个下拉列表中选择某个内容时,我想重新填充第二个下拉列表 在页面加载时,我填充第二个下拉列表,如下所示: // Finds selected value var selectedItem = departureRouteSelectList.First().Value.Substring(2, 2); // Create new selectList for returnRoute var returnRouteSelectList = Model.Rou
// Finds selected value
var selectedItem = departureRouteSelectList.First().Value.Substring(2, 2);
// Create new selectList for returnRoute
var returnRouteSelectList = Model.RoutesListConversely
.Where(x => x.Value.StartsWith(selectedItem))
.Select(x => new SelectListItem() { Text = x.Text, Value = x.Value });
第一行查找最后两个字母,我使用它们在Model.routeslist上进行比较。第二行根据使用这两个字母找到的内容创建列表returnRouteSelectList
可以使用JavaScript中的onChange方法来实现吗?那么,当您选择某个内容时,该方法将运行并重新填充第二个下拉列表
代码:
我设法用jquery和append解决了我的问题 下面的代码实现了这一点:
// On change departure route dropdown list
$("#departureroute").change(function () {
}).change(populateReturnlist);
function populateReturnlist() {
// Clear dropdown for return route
$("#returnroute").empty();
// Gets last two letters.
var word = (this.value).substring(2);
var returnlist = $("#returnroute");
$("#departureroute option").each(function () {
// Gets the value from the departure route
var selectedId = this.value.substring(0, 2);
// Checks so the right routes gets added to list
if (selectedId === word) {
returnlist.append("<option>" + this.text + "</option>")
}
});
};
// Getting value from departure dropdown
$("#departureroute").change(function () {
}).change(populateList);
function populateList() {
// Clear dropdown for return route
$("#returnroute").empty();
// Gets last two letters.
var word = (this.value).substring(2);
// Gets the value from the departure route
var selectedId = $("#departureroute").selectedItem.value;
var returnlist = $("#returnroute");
$("#departureroute").each()
{
if (word == selectedId.substring(2)) {
returnlist.append("#departureroute")
}
}
}
// On change departure route dropdown list
$("#departureroute").change(function () {
}).change(populateReturnlist);
function populateReturnlist() {
// Clear dropdown for return route
$("#returnroute").empty();
// Gets last two letters.
var word = (this.value).substring(2);
var returnlist = $("#returnroute");
$("#departureroute option").each(function () {
// Gets the value from the departure route
var selectedId = this.value.substring(0, 2);
// Checks so the right routes gets added to list
if (selectedId === word) {
returnlist.append("<option>" + this.text + "</option>")
}
});
};