我有一个具有两个列表框的 MVC 应用程序。它使用 jQuery 从一个列表框中移动选定的项目。我想知道如何使用 jQuery 选择第一个列表框中的所有项目以及如何删除第二个列表框中的所有项目?
代码和标记是:
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script>
$(function () {
$("#add").click(function () {
$("#listBoxAvail > option:selected").each(function () {
$(this).remove().appendTo("#listBoxSel");
});
});
$("#remove").click(function () {
$("#listBoxSel > option:selected").each(function () {
$(this).remove().appendTo("#listBoxAvail");
});
});
});
</script>
</head>
<body>
<div>
@using (Html.BeginForm())
{
@Html.ListBoxFor(m => m.SelectedAttributes, Model.Attributes, new {id="listBoxAvail", SIZE = 5} )
<button type="button" id="add">MoveRight</button>
<button type="button" id="remove">"MoveLeft"></button>
<button type="button" id="remove-all">RemAll</button>
<button type="button" id="select-all">SelAll</button>
@Html.ListBoxFor(m => m.SelectedAttributes2, Model.SelectedItems, new { id = "listBoxSel", SIZE = 5})
}
</div>
</body>
最佳答案
要删除所有元素,只需为 listBoxSel
选择所有选项并触发删除按钮的点击操作。
全选相同:
$("#add").click(function () {
$("#listBoxAvail > option:selected").each(function () {
$(this).remove().appendTo("#listBoxSel");
});
});
$("#remove").click(function () {
$("#listBoxSel > option:selected").each(function () {
$(this).remove().appendTo("#listBoxAvail");
});
});
$("#remove-all").on("click", function (event){
$('#listBoxSel option').prop('selected', true);
$("#remove").trigger("click");
})
$("#select-all").on("click", function (event){
$('#listBoxAvail option').prop('selected', true);
$("#add").trigger("click");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select option multiple="true" id="listBoxAvail">
<option>1</option>
<option>2</option>
</select>
<input type="button" id="add" value="add">
<input type="button" id="select-all" value="select all">
<input type="button" id="remove" value="remove">
<input type="button" id="remove-all" value="remove all">
<select option multiple="true" id="listBoxSel">
</select>
更新:
正如 Stephen Muecke 在下面的评论线程中所建议的,更合适的全选解决方案
$('#move').click(function(){
$('#first option').appendTo($('#second'));
});
参见 fiddle
关于javascript - MVC 列表框如何使用 jQuery 来选择所有,删除所有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26488616/