簡體   English   中英

MVC Listbox我如何使用jQuery選擇全部,刪除全部

[英]MVC Listbox how do I use jQuery to select all, remove all

我有一個具有兩個列表框的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選中所有選項, 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'));
});

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM