首页 > 解决方案 > 我怎样才能把所有的复选框都放在这个代码中

问题描述

        <table class="table table-striped grid-table">
        <tr>
            <th>object</th>
            <th>design</th>
            <th></th>
        </tr>
        @foreach (var item in (IEnumerable<cit.Models.getUsersOrgUnit_Result>)Model)
        {
            <tr>
                <td>@item.idorgunit</td>
                <td>@item.orgunitname</td>
                <td>



       @*@Html.CheckBox(item.id.ToString(), item.iduser == ViewBag.iduser ? true :false, new {           
             idorgunit = item.idorgunit, @class = "chkorgunit" })*@       

                    <div class="pure-checkbox">
                        <input type="checkbox" idorgunit="@item.idorgunit" class="chkorgunit" checked="@(item.iduser == ViewBag.iduser ? true : false)" name="@item.id.ToString()" id="@item.id.ToString()" />
                        <label for="@item.id.ToString()"></label>
                    </div>



                </td>
            </tr>
        }
    </table>

我需要为复选框创建按钮全选,然后取消全选。我的清单很长,所以我需要这个解决方案来轻松完成。

标签: htmlasp.net

解决方案


这是一个只有 js 的解决方案。您也可以使用 JQuery 来完成。

在您的复选框中放置一个类(或使用现有的类)。它将允许您获取所有复选框(在我的示例中ckBox)并添加一个带有 onClick 事件处理程序的按钮

    <input type="checkbox" class="ckBox"  id="vehicle1" name="vehicle1" value="Bike">

    <input type="checkbox" class="ckBox" id="vehicle2" name="vehicle2" value="Car">

    <input type="checkbox" class="ckBox" id="vehicle3" name="vehicle3" value="Boat">


    <button id="selectOrUnselect" onClick="toggleSelect()">select</button>
    <script>

        // var used to toggle 
        let allSelected = true

        // get the button, use to change the inside text
        const btnSelect =  document.getElementById("selectOrUnselect")

        // get all the checkboxes
        const ckBoxes = document.getElementsByClassName("ckBox")

        function toggleSelect(){
            // change check to uncheck or uncheck to check
            for(let i = 0 ; i < ckBoxes.length; ++i){
                ckBoxes[i].checked = allSelected;
            }
            // change button text 
            if(allSelected){
               btnSelect.innerText = "Unselect"
            }else{
                btnSelect.innerText = "select"
            }
            allSelected = !allSelected
        }

    </script>

推荐阅读