javascript 在另一个 CheckBox 的基础上选中取消选中所有 CheckBoxes
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22663496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check uncheck all CheckBoxes on the basis of another CheckBox
提问by Suhaib Janjua
I want to select and unselect all checkboxes when user clicks on the first checkbox (All). And if user unchecks any checkbox, then only that checkbox and the first checkbox (All)should be unchecked and no change to the remaining checkboxes.
当用户单击第一个复选框(All)时,我想选择和取消选择所有复选框。如果用户取消选中任何复选框,则只应取消选中该复选框和第一个复选框(全部),其余复选框不做任何更改。
I have a Checkboxlist
in my page which I'm populating dynamically.
Checkboxlist
我的页面中有一个动态填充的页面。
<asp:CheckBoxList runat="server" ID="cbExtList" />
Code Behind
背后的代码
private Extensions _extension = new Extensions();
private ExtCollection _extCollection = new ExtCollection();
_extCollection = _extension.GetAll();
Dictionary<int, string> dExtensions = new Dictionary<int, string>();
dExtensions.Add(0, "All");
foreach (Extensions ext in _extCollection)
{
dExtensions.Add(ext.ID, ext.Extension);
}
this.cbExtList.DataSource = dExtensions;
this.cbExtList.DataTextField = "Value";
this.cbExtList.DataValueField = "Key";
this.cbExtList.DataBind();
Now everything is working fine. I just want to select all Extensions when I click on the first checkbox "All" in this Checkboxlist
.
现在一切正常。我只想在单击此文件中的第一个复选框“全部”时选择所有扩展Checkboxlist
。
This is what I tried with code behind approach.
这就是我尝试使用代码隐藏方法的方法。
With the OnSelectedIndexChanged
and setting the AutoPostBack = True
随着OnSelectedIndexChanged
和设置AutoPostBack = True
<asp:CheckBoxList runat="server" ID="cbExtList" OnSelectedIndexChanged="cbExtList_OnSelectedIndexChanged" AutoPostBack="True" />
protected void cbExtList_OnSelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (Convert.ToInt32(this.cbExtList.SelectedItem.Value) == 0)
{
foreach (ListItem li in cbExtList.Items)
{
li.Selected = true;
}
}
else
{
foreach (ListItem li in cbExtList.Items)
{
li.Selected = false;
}
}
}
catch (Exception ex)
{
Monitoring.WriteException(ex);
}
}
采纳答案by Suhaib Janjua
jQuery way to do it.
jQuery 的方式来做到这一点。
This is the only jQuery code that I need to achieve the given functionality.
这是我实现给定功能所需的唯一 jQuery 代码。
$(document).ready(function() {
$('[id$=checkAllExts]').click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
$("[id*=cbExtList_]").change(function () {
if ($('input[id*=cbExtList_][type=checkbox]:checked').length == $('input[id*=cbExtList_][type=checkbox]').length) {
$('[id$=checkAllExts]').prop('checked', true);
} else {
$('[id$=checkAllExts]').prop('checked', false);
}
});
});
To get IDs of the ASP.NET controls, I used the jQuery attribute selectors which is a better and simple straight way.
为了获取 ASP.NET 控件的 ID,我使用了 jQuery 属性选择器,这是一种更好、更简单的直接方法。
[name$="value"]
[名称$="值"]
Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.
选择具有以给定字符串结尾的值的指定属性的元素。比较区分大小写。
[name*="value"]
[名称*="值"]
Selects elements that have the specified attribute with a value containing a given substring.
选择具有包含给定子字符串的值的指定属性的元素。
So $('[id$=checkAllExts]')
returns me the parent checkbox only on which I select/deselect all checkboxes.
所以只$('[id$=checkAllExts]')
返回我选择/取消选择所有复选框的父复选框。
And $('[id$=cbExtList_]')
returns me all the checkbox except the parent checkbox and I perform my actions accordingly.
并$('[id$=cbExtList_]')
返回除父复选框之外的所有复选框,然后我相应地执行我的操作。
Old Answer
旧答案
The Solution of checking and unchecking CheckBoxList
with JavaScript on client side.
CheckBoxList
在客户端使用 JavaScript检查和取消检查的解决方案。
JavaScript way to do it.
JavaScript 的方式来做到这一点。
<script type="text/javascript">
var Counter;
function ExtAll(CheckBox)
{
//Get target base & child control.
var TargetBaseControl = document.getElementById('<%= this.leftCB.ClientID %>');
var TargetChildControl = "cbExtList";
//Get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
//Checked/Unchecked all the checkBoxes.
for (var n = 0; n < Inputs.length; ++n) {
if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
Inputs[n].checked = CheckBox.checked;
//Reset Counter
}
Counter = CheckBox.checked ? TotalChkBx : 0;
}
function ChildClick(CheckBox, HCheckBox)
{
//get target base & child control.
var HeaderCheckBox = document.getElementById(HCheckBox);
//Modifiy Counter;
if(CheckBox.checked && Counter < TotalChkBx)
Counter++;
else if(Counter > 0)
Counter--;
//Change state of the header CheckBox.
if(Counter < TotalChkBx)
HeaderCheckBox.checked = false;
else if(Counter == TotalChkBx)
HeaderCheckBox.checked = true;
}
</script>
I added a checkbox before my checkboxlist to use its reference to select/unselect the checkboxlist.
On that checkbox I'm calling the JavaScript function when onclick
event happens.
我在复选框列表之前添加了一个复选框,以使用其引用来选择/取消选择复选框列表。在那个复选框上,我在onclick
事件发生时调用 JavaScript 函数。
<div id="leftCB" class="lbl" style="padding-left: 0px;" runat="server">
<asp:CheckBox runat="server" ID="checkAllExts" Text="All" onclick="javascript:ExtAll(this);" />
<asp:CheckBoxList runat="server" ID="cbExtList" />
</div>
Code Behind
背后的代码
private Extensions _extension = new Extensions();
private ExtCollection _extCollection = new ExtCollection();
_extCollection = _extension.GetAll();
Dictionary<int, string> dExtensions = new Dictionary<int, string>();
foreach (Extensions ext in _extCollection)
{
dExtensions.Add(ext.ID, ext.Extension);
// Added the below line for the functionality of CheckBoxList
// which adds an attribute with all of the checkboxes in the CheckBoxList
this.cbExtList.Attributes["onclick"] = string.Format("javascript:ChildClick(this,'{0}');", this.checkAllExts.ClientID);
}
this.cbExtList.DataSource = dExtensions;
this.cbExtList.DataTextField = "Value";
this.cbExtList.DataValueField = "Key";
this.cbExtList.DataBind();
回答by TylerH
If you need to check all checkboxes on checking of an "all" checkbox and uncheck them all upon unchecking of it, but also needed to disableeach checkbox (aside from the "all") checkbox when the "all" checkbox was checked, this code should work for you. It has the added benefit of not requiring JavaScript/jQuery, too.
如果您需要在选中“全部”复选框时选中所有复选框,并在取消选中它时取消选中它们,但还需要在选中“全部”复选框时禁用每个复选框(除了“全部”)复选框,这代码应该适合你。它还有一个额外的好处,那就是不需要 JavaScript/jQuery。
Here's the .aspx code (for this scenario I have nine facilities that can be selected in any combination):
这是 .aspx 代码(对于这个场景,我有九个可以任意组合选择的设施):
<asp:Label ID="lblFacility" AssociatedControlID="chkFacility" runat="server" Text="Facility: "></asp:Label>
<asp:CheckBoxList ID="chkFacility" runat="server" OnSelectedIndexChanged="chkFacility_SelectedIndexChanged">
<asp:ListItem Value="All" Text="All"></asp:ListItem>
<asp:ListItem Value="Location1" Text="Location 1"></asp:ListItem>
<asp:ListItem Value="Location2" Text="Location 2"></asp:ListItem>
<asp:ListItem Value="Location3" Text="Location 3"></asp:ListItem>
<asp:ListItem Value="Location4" Text="Location 4"></asp:ListItem>
<asp:ListItem Value="Location5" Text="Location 5"></asp:ListItem>
<asp:ListItem Value="Location6" Text="Location 6"></asp:ListItem>
<asp:ListItem Value="Location7" Text="Location 7"></asp:ListItem>
<asp:ListItem Value="Location8" Text="Location 8"></asp:ListItem>
<asp:ListItem Value="Location9" Text="Location 9"></asp:ListItem>
</asp:CheckBoxList>
And the Code Behind:
以及背后的代码:
protected void chkFacility_SelectedIndexChanged(object sender, EventArgs e) {
//disables all the checkboxes when "All" is selected
if (chkFacility.SelectedIndex==0) {
foreach(ListItem aListItem in chkFacility.Items) {
aListItem.Selected = true;
if (aListItem.Value != "All") {
aListItem.Enabled = false;
}
}
} else if (chkFacility.SelectedIndex > 0) {
var i = 0;
foreach(ListItem aListItem in chkFacility.Items) {
if (aListItem.Selected) {
i++;
}
}
//with the i++ check above, this handles unchecking every checkbox when each location is selected and the "All" checkbox is unchecked
if (i == 9) {
foreach(ListItem aListItem in chkFacility.Items) {
aListItem.Selected = false;
aListItem.Enabled = true;
}
//disables the "All" checkbox in all other cases where 8 or fewer of the 9 locations are selected
} else {
foreach(ListItem aListItem in chkFacility.Items) {
if (aListItem.Value == "All") {
aListItem.Enabled = false;
}
}
}
//if no locations are selected after PostBack, make sure all checkboxes are enabled
} else if (chkFacility.SelectedIndex == -1) {
foreach(ListItem aListItem in chkFacility.Items) {
aListItem.Enabled = true;
}
}
}
One caveat to this implementation, though, is that the code for whether all locations are selected will also clear out the selection if they're all currently selected by manually checking each one. When I was writing the code for work, this edge case was an acceptable risk considering it was unlikely and considering that if all locations need to be selected, the user should be checking the "All" checkbox instead, anyway.
但是,对此实现的一个警告是,是否选择所有位置的代码也将清除选择,如果它们当前都通过手动检查每个位置都已选择。当我编写工作代码时,这种边缘情况是一个可接受的风险,因为它不太可能,并且考虑到如果需要选择所有位置,无论如何用户应该选中“全部”复选框。
回答by Seany84
I have put together an example using jQuery and Javascript to check/uncheck items in a checkboxlist based on the checked state of the first or All
check box.
我已经整理了一个使用 jQuery 和 Javascript 的示例,根据第一个或All
复选框的选中状态来选中/取消选中复选框列表中的项目。
ASPX:
ASPX:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
var checkedState = false;
function checkAll() {
$("input[id^=cblMultiple]").each(function () {
if ($(this).val() == 0) {
checkedState = $(this).is(":checked")
}
else {
$(this).attr("checked", checkedState)
}
//console.log(checkedState);
//console.log($(this).val());
});
}
$(document).ready(function () {
$("input[id^=cblMultiple]").each(function () {
if ($(this).val() == 0) {
$(this).on("click", checkAll);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBoxList runat="server" ID="cblMultiple"/>
</form>
</body>
</html>
Code Behind
背后的代码
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cblMultiple.Items.Add(new ListItem("All", "0"));
for (int i = 1; i < 11; i++)
{
cblMultiple.Items.Add(new ListItem("All" + i, i.ToString()));
}
}
}
回答by Karim AG
loop through the list and set the Selected value of the items to true/false:
循环遍历列表并将项目的 Selected 值设置为 true/false:
for (int i = 0; i < cbExtList.Items.Count; i++)
{
cbExtList.Items[i].Selected = true;
}