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.
I have a Checkboxlist
in my page which I'm populating dynamically.
<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
.
This is what I tried with code behind approach.
With the OnSelectedIndexChanged
and setting the 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);
}
}
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.
I have a Checkboxlist
in my page which I'm populating dynamically.
<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
.
This is what I tried with code behind approach.
With the OnSelectedIndexChanged
and setting the 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);
}
}
Share
Improve this question
edited Feb 8, 2018 at 12:49
Suhaib Janjua
asked Mar 26, 2014 at 14:06
Suhaib JanjuaSuhaib Janjua
3,57216 gold badges69 silver badges87 bronze badges
10
- 1 What method are you currently using? If you could post the code you are using now to attempt to check/uncheck all the checkboxes it would help in diagnosing your issue – Pseudonym Commented Mar 26, 2014 at 14:14
- @PseudoNym01 I edited my question. I Tried it from code behind, but not achieve the functionality properly. And from client side, I already mentioned the links that I already tried. – Suhaib Janjua Commented Mar 26, 2014 at 14:22
- 1 You tagged the question w/ javascript and jquery but from what I can tell, you're not attempting to use either... You can do this pretty easily from the jquery if that's a viable option – Rikon Commented Mar 26, 2014 at 14:24
- @Rikon, I think that if he'll do this in the client side, the propery "Selected" of the checkboxes will not be updated in the server side, isn't it? – ronen Commented Mar 26, 2014 at 14:26
- My code it working fine for selecting all and unselecting all. but it has a problem that on unchecking any checkbox except the first, it won't unchecking it. – Suhaib Janjua Commented Mar 26, 2014 at 14:26
4 Answers
Reset to default 2jQuery way to do it.
This is the only jQuery code that I need to achieve the given functionality.
$(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.
[name$="value"]
Selects elements that have the specified attribute with a value ending exactly with a given string. The parison 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.
And $('[id$=cbExtList_]')
returns me all the checkbox except the parent checkbox and I perform my actions accordingly.
Old Answer
The Solution of checking and unchecking CheckBoxList
with JavaScript on client side.
JavaScript way to do it.
<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.
<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();
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.
ASPX:
<html xmlns="http://www.w3/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn./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()));
}
}
}
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 disable each 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.
Here's the .aspx code (for this scenario I have nine facilities that can be selected in any bination):
<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.
loop through the list and set the Selected value of the items to true/false:
for (int i = 0; i < cbExtList.Items.Count; i++)
{
cbExtList.Items[i].Selected = true;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744113547a4559065.html
评论列表(0条)