An ASP.NET Blog
I work for Microsoft and help people and businesses make better use of technolgy to realize their full potential. The opinions mentioned herein are solely mine and do not reflect those of my employer.

ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Saturday, March 25, 2006 7:59 AM

ASP.NET 2.0 has introduced many new promising controls and TreeView is one among them. There has always been a requirement for Tree Control in earlier versions and it was quite hard to manage them with either the third party controls or the lighter version - IE Webcontrols.

Thanks to ASP.NET team, the 2.0 version rolled out with a built-in Treeview Control. The TreeView has many built-in features such as showing a checkbox for all the Tree Nodes. Node level formating, style, etc., Enabling the ShowCheckBoxes="All" property sets it to show a checkbox for all the nodes. The other options are Leaf, None, Parent and Root which show checkboxes at the respective node levels. None doesnt display CheckBoxes.

When we set ShowCheckBoxes="All", we would like to provide a feature where people can select the checkbox on the Root Node so that all the other checkboxes are checked automatically. Basically, when the parent node is checked, all the child nodes should be checked automatically.

It would be intuitive to accomplish this task at the client side without involving a postback.

The following code snippet helps in accomplishing the same.

TreeView Declaration

<asp:TreeView ID="TreeView1" Runat="server" DataSourceID="XmlDataSource1" onclick="client_OnTreeNodeChecked();" ShowCheckBoxes="all">

<DataBindings>

<asp:TreeNodeBinding DataMember="Category" ValueField="ID" TextField="Name"></asp:TreeNodeBinding>

<asp:TreeNodeBinding DataMember="Description" ValueField="Value" TextField="Value"></asp:TreeNodeBinding>

</DataBindings>

</asp:TreeView>


In the above TreeView declaration Code, you can find the property onclick="client_OnTreeNodeChecked();" event which actually is the JavaScript function which would accomplish this task.

The Javascript Code snippet is as follows:-

<script language="javascript" type="text/javascript">
function client_OnTreeNodeChecked()
{
var obj = window.event.srcElement;
var treeNodeFound = false;
var checkedState;
if (obj.tagName == "INPUT" && obj.type == "checkbox") {
var treeNode = obj;
checkedState = treeNode.checked;
do
{
obj = obj.parentElement;
} while (obj.tagName != "TABLE")
var parentTreeLevel = obj.rows[0].cells.length;
var parentTreeNode = obj.rows[0].cells[0];
var tables = obj.parentElement.getElementsByTagName("TABLE");
var numTables = tables.length
if (numTables >= 1)
{
for (i=0; i < numTables; i++)
{
if (tables[i] == obj)
{
treeNodeFound = true;
i++;
if (i == numTables)
{
return;
}
}
if (treeNodeFound == true)
{
var childTreeLevel = tables[i].rows[0].cells.length;
if (childTreeLevel > parentTreeLevel)
{
var cell = tables[i].rows[0].cells[childTreeLevel - 1];
var inputs = cell.getElementsByTagName("INPUT");
inputs[0].checked = checkedState;
}
else
{
return;
}
}
}
}
}
}
</script>

You may find that in Visual Studio 2005 the onclick method declared in the TreeView is underlined as an error, but still it would work.

This is a simple but sometimes frustrating requirement and hope this benefits similar requirements.

Thanks to
mtntime77 for posting the original idea.

Cheers and Happy TreeViewing.


Feedback

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Great code! Exactly what I'm looking for :-)

Can you post the opposite code (ie: uncheck a child node unchecks all parents but checking a child node does NOT check all parents)?

Thanks! 3/29/2006 12:43 AM | Rich

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hello...
I've worked a little bit more on the above solution with other forum members help...

check it out at...
http://forums.asp.net/1243475/ShowThread.aspx#1243475

I need the complete checkboxes behavoir too...please post if anybody has any ideas or solutions....Thanks! 3/31/2006 12:15 PM | Kiks

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

check out the same thread, above...I've posted a followup/final solution... 3/31/2006 8:28 PM | Kiks

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

function goDeeperChecked(obj)
{
var chk1 = true;
//Get the mom.
var head1 = obj.parentElement.previousSibling;
//no rows, cant do my work.
if(obj.rows == null)
{return ;}

//This is how may rows are at this level.
var pTreeLevel1 = obj.rows[0].cells.length;
//Are we a mommy?
if(head1.tagName == "TABLE")
{
//Get the list of rows ahead of us.
var tbls = obj.parentElement.getElementsByTagName("TABLE");
//get the count of that list.
var tblsCount = tbls.length;

//determine if any of the rows underneath are unchecked.
for (i=0; i < tblsCount; i++)
{
var childTreeLevel = tbls[i].rows[0].cells.length;
if (childTreeLevel = pTreeLevel1)
{
var chld = tbls[i].getElementsByTagName("INPUT");
if (chld[0].checked == false)
{
chk1 = false;
break;
}
}
}

var nd = head1.getElementsByTagName("INPUT");
nd[0].checked = chk1;
//do the same for the level above
goDeeperChecked(obj.parentElement);
}
else
{
return;
}
}
function goDeeper(check, obj)
{

//head1 gets the parent node of the unchecked node
var head = obj.parentElement.previousSibling;

if(head.tagName == "TABLE")
{
//checks for the input tag which consists of checkbox
var matchElement = head.getElementsByTagName("INPUT");

//matchElement1[0] gives us the checkbox and it is unchecked
matchElement[0].checked = false;
}
else
{
head = obj.parentElement.previousSibling;
}

if(head.tagName == "TABLE")
{
goDeeper(check, obj.parentElement);
}

else
{
return;
}
}
function treeViewCheck()
{
// obj gives us the node on which check or uncheck operation has performed
var obj = window.event.srcElement;

var treeNodeFound = false;

var checkedState;


//checking whether obj consists of checkbox to avoid exception

if (obj.tagName == "INPUT" && obj.type == "checkbox")
{
var treeNode = obj;
checkedState = treeNode.checked;

//work our way back to the parent <table> element

do
{
obj = obj.parentElement;
}
while (obj.tagName != "TABLE")

var parentTreeLevel = obj.rows[0].cells.length;
var parentTreeNode = obj.rows[0].cells[0];

//get all the TreeNodes inside the TreeView (the parent <div>)
var tables = obj.parentElement.getElementsByTagName("TABLE");

//checking for any node is checked or unchecked during operation
if(obj.tagName == "TABLE")
{
// if any node is unchecked then their parent node are unchecked

if (!treeNode.checked)
{
goDeeper(false, obj);
} //end if - unchecked
//total number of TreeNodes
var numTables = tables.length

if (numTables >= 1)
{
//cycle through all the TreeNodes
//until we find the TreeNode we checked

for (i=0; i < numTables; i++)
{
if (tables[i] == obj)
{
treeNodeFound = true;
i++;
if (i == numTables)
{
//if we're on the last TreeNode, we are done
break;
}
}
if (treeNodeFound == true)
{
var childTreeLevel = tables[i].rows[0].cells.length;
if (childTreeLevel > parentTreeLevel)
{
var cell = tables[i].rows[0].cells[childTreeLevel - 1];
//set the checkbox to match the checkedState

var inputs = cell.getElementsByTagName("INPUT");
inputs[0].checked = checkedState;
}

else
{
//if any of the preceding TreeNodes are not deeper stop
break;
}
} //end if

}//end for
} //end if - numTables >= 1

// if all child nodes are checked then their parent node is checked
if (treeNode.checked)
{
goDeeperChecked(obj);
}//end if - checked

} //end if - tagName = TABLE

} //end if

} //end function
4/12/2006 4:27 PM | Jake

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Did anyone else find that this works fine in IE but not in Firefox?

It seems that the OnClick event is firing the client_OnTreeNodeChecked() script.

Anyone got any ideas why \ a work around for this? 4/18/2006 7:28 AM | Gareth

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Sorry meant to say:
It seems that the OnClick event *isn't* firing the client_OnTreeNodeChecked() script. 4/18/2006 7:36 AM | Gareth

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hii,

function client_OnTreeNodeChecked(event)
{
var TreeNode = event.srcElement || event.target ;

if (TreeNode.tagName == "INPUT" && TreeNode.type == "checkbox")
{
if(TreeNode.checked)
{
alert(TreeNode.title)
}
alert(TreeNode.value)
}
}

I am using the above code to get selected nodes at client side, and it is working fine but the problem is that I want to get Value(TreeNode.Value) of the current node instead of text(TreeNode.title gives TreeNode.Text), TreeNode.value is always returning ‘on’. Please tell me how I can retrieve Value of the node...

Cheerio
Abhishek
5/6/2006 11:19 AM | Abhishek

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

// JScript File

function goDeeperUnChecked(obj)
{
var chk1 = false;
//Get the mom.
var head1 = obj.parentElement.previousSibling;
//no rows, cant do my work.
if(obj.rows == null)
{return ;}

//This is how may rows are at this level.
var pTreeLevel1 = obj.rows[0].cells.length;

//Are we a mommy?
if(head1.tagName == "TABLE")
{
//Get the list of rows ahead of us.
var tbls = obj.parentElement.getElementsByTagName("TABLE");
//get the count of that list.
var tblsCount = tbls.length;

//determine if any of the rows underneath are unchecked.
for (i=0; i < tblsCount; i++)
{
var childTreeLevel = tbls[i].rows[0].cells.length;
if (childTreeLevel = pTreeLevel1)
{
var chld = tbls[i].getElementsByTagName("INPUT");
if (chld[0].checked == true)
{
chk1 = true;
break;
}
}
}

var nd = head1.getElementsByTagName("INPUT");
nd[0].checked = chk1;
//do the same for the level above
goDeeperUnChecked(obj.parentElement);
}
else
{
return;
}
}


function goDeeper(obj)
{

//head1 gets the parent node of the checked node
var head = obj.parentElement.previousSibling;

if(head.tagName == "TABLE")
{
//checks for the input tag which consists of checkbox
var matchElement = head.getElementsByTagName("INPUT");

//matchElement[0] gives us the checkbox and it is checked
//something is wrong here, fixed
if (matchElement.length>0){
matchElement[0].checked = true;
}

}
else
{

head = obj.parentElement.previousSibling;
}

if(head.tagName == "TABLE")
{
goDeeper(obj.parentElement);
}

else
{
return;
}
}
function treeViewCheck()
{
// obj gives us the node on which check or uncheck operation has performed
var obj = window.event.srcElement;

var treeNodeFound = false;

var checkedState;


//checking whether obj consists of checkbox to avoid exception

if (obj.tagName == "INPUT" && obj.type == "checkbox")
{
var treeNode = obj;
checkedState = treeNode.checked;


//work our way back to the parent <table> element

do
{
obj = obj.parentElement;
}
while (obj.tagName != "TABLE")

var parentTreeLevel = obj.rows[0].cells.length;
var parentTreeNode = obj.rows[0].cells[0];

//get all the TreeNodes inside the TreeView (the parent <div>)
var tables = obj.parentElement.getElementsByTagName("TABLE");

//checking for any node is checked or unchecked during operation
if(obj.tagName == "TABLE")
{

// Modified - if any node is checked then their parent node is checked
if (treeNode.checked)
{
goDeeper(obj);
} //end if - checked

//total number of TreeNodes
var numTables = tables.length

if (numTables >= 1)
{
//cycle through all the TreeNodes
//until we find the TreeNode we checked

for (i=0; i < numTables; i++)
{
if (tables[i] == obj)
{
treeNodeFound = true;
i++;
if (i == numTables)
{
//if we're on the last TreeNode, we are done
break;
}
}
if (treeNodeFound == true)
{

var childTreeLevel = tables[i].rows[0].cells.length;
if (childTreeLevel > parentTreeLevel)
{
var cell = tables[i].rows[0].cells[childTreeLevel - 1];
//set the checkbox to match the checkedState

var inputs = cell.getElementsByTagName("INPUT");
inputs[0].checked = checkedState;

}

else
{
//if any of the preceding TreeNodes are not deeper stop
break;

}
} //end if

}//end for
} //end if - numTables >= 1


//Modified - If all child nodes are unchecked then their parent node is unchecked

if (!treeNode.checked)
{
goDeeperUnChecked(obj);
}//end if - unChecked


} //end if - tagName = TABLE

} //end if

} //end function

5/15/2006 2:37 PM | a better version

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

I get an error "event has no properties" when I run "window.event.srcElement;" in Firefox.

It works perfectly in Explorer, but how do I make window.event.srcElement work in Firefox?

Thank you, Mads 6/6/2006 2:26 AM | PhiMix

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

One more thing,

var nd = head1.getElementsByTagName("INPUT");
nd[0].checked = chk1;

should be changed to:

var nd = head1.getElementsByTagName("INPUT");
// Check if there are any elements first
if (nd.length>0){
nd[0].checked = chk1;
}
6/13/2006 12:31 PM | Cynthia

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Great code.
I'm facing a problem that,even if all the parent nodes are deselected, grand parent node is not deselected. Could any ony help me to find a solution for this.
6/20/2006 2:39 AM | Kesav

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Thanks this came to great use, saved me loads of time.. 10/4/2006 8:51 AM | Trevor

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

goDeeperUnChecked();
goDeeper();
treeViewCheck();

So great,thx.
But its a pity it doesnt work for grandpa. 11/24/2006 12:46 AM | Seb

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

I discovered that the html that is emitted by the treeview control can vary when using the predefined treeview formatting settings. I did not test all of the settings, but did discover that the javascript does not work with some settings. 12/23/2006 12:41 PM | JoeS

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Thank you! Thank you! That code is beautifual. I've had multiple failed attempts at accomplishing javascript that would do just this. 12/28/2006 5:43 PM | Brittany

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Any idea how to make that javascript work with Firefox? 12/28/2006 5:51 PM | Brittany

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Thanks! 1/2/2007 7:07 PM | Nick

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hi Great code...

But I want little more functionality...

Now with t his code, when I Unccheck node then it only uncheck the PArent Node...what to do If i wants to uncheck further parent node as no any child node of that parent node is selected...

And also i want to check all the child Nodes on click of Parent node..

Thanks in Advance...

Tejas 1/6/2007 6:26 AM | Tejas

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Please can anyone help me on this
According to the functionality i need,when all checkboxes of child node is unchecked only then checkboxes of the parent node should be unchecked
Please can anybody provide with a relevant script for the same 1/17/2007 8:57 AM | Payal

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hi Harish,

Just a quick question on this:

Does this javascript work on treeview control populated by XMLDataSource only??

I am trying to do the same thing, check and uncheck all on the treeview control populated from database..however, the above script does not seem to WORK!

any ideas? 2/8/2007 1:49 PM | Lakshmi Murthy

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hi,
Harish sir,
Ur code is tremendous,as i am beginner in .net, please send me that category xml file which is used in treeview,and please tell me where i have to place xml file,wiating for ur reply
thank u
Vishwanath 2/15/2007 6:22 AM | vishwanath

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hi,
I am getting below error

The DataSourceID of 'TreeView1' must be the ID of a control of type IHierarchicalDataSource. A control with ID 'XmlDataSource1' could not be found.
2/15/2007 6:28 AM | Vishwanath

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hi
In a tree view i am binding the tree view from the back end when the page is loaded.here when a user check the Prent Node then automatically all the child node will be checked and if the user is unchecked the parent node then all the child nodes will ne unchecked.i am placing the above code in .aspx and i am not rectifying the problem can u pls help. 2/22/2007 5:31 AM | Satish Babu Dasari

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

I am using the above code to get selected nodes at client side, and it is working fine but It is working only IE browser, it isn’t work mozhila firebox Please tell me how I can modify that code
3/9/2007 8:36 AM | Kalimuthu

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

...1. error...

if (childTreeLevel = pTreeLevel1)
{
var chld = tbls[i].getElementsByTagName("INPUT");
if (chld[0].checked == false)
{
chk1 = false;
break;
....right....
if (childTreeLevel == pTreeLevel1)
{
var chld = tbls[i].getElementsByTagName("INPUT");
if (chld[0].checked == false)
{
chk1 = false;
break;


...2.error...
var nd = head1.getElementsByTagName("INPUT");
nd[0].checked = chk1;
//do the same for the level above
goDeeperUnChecked(obj.parentElement);
}
else
{
return;
}
}
....right....
var nd = head1.getElementsByTagName("INPUT");
nd[0].checked = chk1;
//do the same for the level above
goDeeperUnChecked(obj.parentElement.previousSibling);
}
else
{
return;
}
}


3/13/2007 2:11 PM | slavo

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Anybody help me
I am using the above code to get selected nodes at client side, and it is working fine but It is working only IE browser, it isn’t work mozhila firebox Please tell me how I can modify that code. 3/13/2007 2:24 PM | Kalimuthu

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hi,

There have been problems with the above script - the check/uncheck behavior is implemented only upto one level up the hierarchy. I've posted the complete solution

check here: http://forums.asp.net/p/976122/1733193.aspx#1733193 5/31/2007 2:43 AM | pushp

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Hi,

is it possible to get the value of the node (TreeNode.Value) on the client side? The TreeNode.Text is possible through "title", but I need the value...please give me some light...

Cheers,
na-rocha 6/10/2007 6:13 PM | na-rocha

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Great Article

helped me a lot 6/27/2007 12:52 AM | Sushilkumar Pandey

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Does anyone know how to make this working with firefox? 8/19/2007 9:52 PM | Radu

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Here you go, the asp.net forums has code that works in both IE and Firefox. It also unchecks the parent if you uncheck one of the siblings. I've tested in IE 7 and Firefox 2.0.0.9 and it works well in both:

http://forums.asp.net/p/976122/1733193.aspx#1733193

And here is the code they used:

//************************** Treeview Parent-Child check behaviour ****************************//
function OnTreeClick(evt)
{
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
if(isChkBoxClick)
{
var parentTable = GetParentByTagName("table", src);
var nxtSibling = parentTable.nextSibling;
if(nxtSibling && nxtSibling.nodeType == 1)//check if nxt sibling is not null & is an element node
{
if(nxtSibling.tagName.toLowerCase() == "div") //if node has children
{
//check or uncheck children at all levels
CheckUncheckChildren(parentTable.nextSibling, src.checked);
}
}
//check or uncheck parents at all levels
CheckUncheckParents(src, src.checked);
}
}
function CheckUncheckChildren(childContainer, check)
{
var childChkBoxes = childContainer.getElementsByTagName("input");
var childChkBoxCount = childChkBoxes.length;
for(var i = 0; i<childChkBoxCount; i++)
{
childChkBoxes[i].checked = check;
}
}
function CheckUncheckParents(srcChild, check)
{
var parentDiv = GetParentByTagName("div", srcChild);
var parentNodeTable = parentDiv.previousSibling;

if(parentNodeTable)
{
var checkUncheckSwitch;

if(check) //checkbox checked
{
var isAllSiblingsChecked = AreAllSiblingsChecked(srcChild);
if(isAllSiblingsChecked)
checkUncheckSwitch = true;
else
return; //do not need to check parent if any(one or more) child not checked
}
else //checkbox unchecked
{
checkUncheckSwitch = false;
}

var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
if(inpElemsInParentTable.length > 0)
{
var parentNodeChkBox = inpElemsInParentTable[0];
parentNodeChkBox.checked = checkUncheckSwitch;
//do the same recursively
CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
}
}
}
function AreAllSiblingsChecked(chkBox)
{
var parentDiv = GetParentByTagName("div", chkBox);
var childCount = parentDiv.childNodes.length;
for(var i=0; i<childCount; i++)
{
if(parentDiv.childNodes[i].nodeType == 1) //check if the child node is an element node
{
if(parentDiv.childNodes[i].tagName.toLowerCase() == "table")
{
var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
//if any of sibling nodes are not checked, return false
if(!prevChkBox.checked)
{
return false;
}
}
}
}
return true;
}
//utility function to get the container of an element by tagname
function GetParentByTagName(parentTagName, childElementObj)
{
var parent = childElementObj.parentNode;
while(parent.tagName.toLowerCase() != parentTagName.toLowerCase())
{
parent = parent.parentNode;
}
return parent;
}
12/19/2007 6:39 AM | Dustin Horne

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

The below javascript is the simple to check all the checkboxes in a treeview control

function UnCheckAllCheckBoxes()
{
var ControlToUncheck = document.getElementById('ctl00_maincontent_WTrVwDivisionHierarchy');
var tables = ControlToUncheck.getElementsByTagName("TABLE");
var iLoop;
for(iLoop = 0; iLoop < tables.length; iLoop++)
{
var check = tables[iLoop].getElementsByTagName("INPUT");
var i;
for(i = 0; i < check.length; i++)
{
if(check[i].type = "checkbox")
{
check[i].checked = true;
}
}
}

} 2/7/2008 9:20 PM | Pradeep

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

Thanks for the owner of first article... 3/17/2008 6:41 PM | Saed Omar

# re: ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

The script works just fine...
great post my friend..!!!

I have another problem, please help me.
1)I want to get the text, value & deapth of the node checked.
2)should alert if its a Root Node.
3)It should be the Leaf node(last node in branch).
and not parent node...!!
4)Should open a page by passing these 3 values ( in modal window )

Can u help me friends ??

Regards,
Mandar 4/10/2008 9:15 PM | Mandar

# Expand node when checked

I have a requirement here...
My treeview has checkboxes at every node.Now when I check a node,it should be expanded...all its sub-nodes and sub-nodes of sub-nodes should be expanded
Pls help me..

Thanx in advance 5/7/2008 8:29 PM | meera

Post a comment





 

Please add 2 and 7 and type the answer here: