Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  195] [ 6]  / answers: 1 / hits: 34186  / 13 Years ago, thu, april 28, 2011, 12:00:00

I have a checkoxlist with a couple of items and an all option. The user can select all and I want this to check off all the options and if they uncheck all it will uncheck all options.



I have accomplished this with the following code.



<script language=javascript type=text/javascript>
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName(input);

alert(chkBoxCount[0].checked);

for(var i=0;i<chkBoxCount.length;i++)
{
chkBoxCount[i].checked = chkBoxCount[0].checked //state;
}

return false;
}
</script>

cblAffiliation.Attributes.Add(onclick, javascript: CheckBoxListSelect (' & cblAffiliation.ClientID & ');)


The issue is that if I select any of the boxes it loops through and then sets them to whatever the all option is. I am having trouble figuring out the best way to get around this.



I want to avoid using a checkbox next to the checkboxlist, then I have to make that line up with the checkboxlist.


More From » .net

 Answers
26

Simply check to see if the box clicked was the all option. If it was, then go ahead and change the rest of the boxes. If it isn't, then check all the options to see if they are all checked so you can update the 'All' checkbox.






EDIT



You might want to use onChange, instead of onClick, onClick will probably be called before the value on the given checkbox is changed.






Code not checked, please forgive syntax problems.



<script language=javascript type=text/javascript>
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName(input);
var clicked = this;

alert(chkBoxCount[0].checked ? 'All is Checked' : 'All is not Checked');
alert(clicked == chkBoxCount[0] ? 'You Clicked All' : 'You Didn't click All');

var AllChecked = true; // Check the all box if all the options are now checked

for(var i = 1;i < chkBoxCount.length; i++)
{
if(clicked == chkBoxCount[0]) { // Was the 'All' checkbox clicked?
chkBoxCount[i].checked = chkBoxCount[0].checked; // Set if so
}
AllChecked &= chkBoxCount[i].checked; // AllChecked is anded with the current box
}

chkBoxCount[0].checked = AllChecked;

return false;
}
</script>

cblAffiliation.Attributes.Add(onchange, javascript: CheckBoxListSelect (' & cblAffiliation.ClientID & ');)

[#92499] Wednesday, April 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braidenv

Total Points: 80
Total Questions: 104
Total Answers: 91

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
;