Set the max number of items that can be selectable in ListBo
本文关键字:be can selectable in ListBo that items the max number of | 更新日期: 2023-09-27 18:21:19
我在一个可以多选的列表框中有一个包含40个结果的列表,但我想将选择的数量限制为某个数字,比如说5。在C#MVC中,我有:
@Html.ListBoxFor(model => model.Location, new SelectList(Model.AllLocations, Model.Location), new { id = "AllLocations" })
在控件上设置此约束的最佳方式是什么?
Javascript。Html没有为此提供任何机制。类似这样的东西:
$(document).ready(function() {
// Add a click event for options in the list.
$('#MyModel_Location option').click(function() {
// Check if the parent has reached the limit of selected items.
if ($(this).parent().val().length > 5) {
// Removed the selected attribute from this option.
$(this).removeAttr("selected");
}
});
});