[英]jquery validate on @Html.DropDownListFor with bootstrap selectpicker
[英]How to select data for @Html.DropDownListFor (selectpicker class) when @Html.DropDownList is updated, by jQuery?
我正在通過ASP.NET-MVC開發Web應用程序。
模型:
public partial class MyModel
{
public string TEST { get; set; }
}
HTML:
@model IList<MyModel>
@Html.DropDownList("dropDownListSelectToAnotherDropDownList", (SelectList)ViewBag.testList[0], null, new { id = "dropDownListSelectToAnotherDropDownList", title = "[--Select to all--]", @class = "selectpicker form-control", data_style = "btn btn-default", data_width = "100%", data_live_search = "true", data_size = "9" })
@for (var i = 0; i < Model.Count; i++)
{
@Html.DropDownListFor(m => Model[i].TEST, (SelectList)ViewBag.testList[i], null, new { id = "dropDownListTest" + i, title = "[--Select Test--]", @class = "selectpicker form-control", data_style = "btn btn-default", data_width = "100%", data_live_search = "true", data_size = "9" })
}
jQuery的:
$('#dropDownListSelectToAnotherDropDownList').on('keyup change', function () {
@for (var i = 0; i < Model.Count; i++)
{
$('dropDownListTest' + i).val($(this).val());
//$('dropDownListTest' + i).selectpicker('val', $(this).val());
}
});
如上面的代碼所示,我將獲得dropDownListSelectToAnotherDropDownList和許多dropDownListTest (例如:dropDownListTest0,dropDownListTest1,...,dropDownListTestN),具體取決於模型的數量。 我想在dropDownListSelectToAnotherDropDownList更改時創建事件。 該事件將從dropDownListSelectToAnotherDropDownList獲取數據,然后將其設置為所有dropDownListTest 。 但這是行不通的。 有人可以幫我建議嗎?
首先,您應該刪除所有id
定義,並為循環內DropDownListFor
創建的<select>
元素使用單獨的類名,例如dropDownListTest
:
@for (var i = 0; i < Model.Count; i++)
{
@Html.DropDownListFor(m => Model[i].TEST, (SelectList)ViewBag.testList[i], null, new { title = "[--Select Test--]",
@class = "selectpicker form-control dropDownListTest", ... })
}
然后,使用jQuery.each()
方法從<select>
元素中以id="dropDownListSelectToAnotherDropDownList"
選定值填充它們。 下面的兩個示例應具有相同的結果:
// example 1
$('#dropDownListSelectToAnotherDropDownList').on('keyup change', function () {
val selectedValue = $(this).val();
$('.dropDownListTest').each(function () {
$(this).val(selectedValue);
})
});
// example 2
$('#dropDownListSelectToAnotherDropDownList').on('keyup change', function () {
val selectedValue = $(this).val();
$.each($('.dropDownListTest'), function () {
$(this).val(selectedValue);
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.