html - 我怎样才能把所有的复选框都放在这个代码中
问题描述
<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>
我需要为复选框创建按钮全选,然后取消全选。我的清单很长,所以我需要这个解决方案来轻松完成。
解决方案
这是一个只有 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>
推荐阅读
- python - 使用 Python 查找所有迷宫解决方案
- gstreamer - 无法使用 PyGObject 将 Nvstreamdemux 链接到 rtph264pay 元素
- google-cloud-platform - 在负载均衡器中仅支持 https
- reactjs - 故事书顺风。我应该如何在故事书中添加顺风
- docker - docker中的多个容器在同一个IP上工作
- angular - 如何根据结果进行可观察的调用?
- javascript - 使用 javascript 和 fflate 从 zip 存档中删除 __MACOSX/ 文件
- kotlin - 初始化后如何更改 Kotlin 中字符串的值?
- python - 从批处理文件启动时“ImportError: DLL load failed while importing _ssl”
- powershell - Powershell:指定电子邮件:密码与随机数据之间