Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

 

Updated the post with the XML File I had used.

I posted this article originally in March 2006 when the ASP.NET 2.0 TreeView had just been released.  This article has received tremendous response (35000 views for this particular post) and also many recommendations / suggestions / corrections as comments.

The script then supported checking/unchecking of children/parents when selecting/deselecting a particular node.  However, in cases of having multiple children and de-selecting one of them, the parent doesn’t automatically get un-selected.  Also there seemed to be a few issues with Firefox, Safari etc.,

So the intent of this post is to publish the best working Java Script (submitted by the community) that fixes the above issues as well as support  multiple browsers and provide a better way of handling the event.  Special thanks to pushp_aspnet for taking the pain to make this script work across multiple browsers and multiple levels.

To begin with, create a blank new ASP.NET Website and in your web form, drag and drop a TreeView control in to the page.  Also, drag and drop an XML DataSource control into your page (this can be found under “Data” tab in the Visual Studio toolbox).

Configure the DataSource to an XML File (I have pasted the XML Code at the end of this post) or any method that returns an XML from your Database etc., Bind the TreeView to the XML DataSource.  Also, set the ShowCheckBox=”All” property for the TreeView.  The sample code looks as below:-

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1" ShowCheckBoxes="All">
        </asp:TreeView>
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Syllabus.xml"></asp:XmlDataSource>

Note, I have set the Datafile to a physical XML file I had which has decent hierarchy of parent/child nodes. (As mentioned earlier, I have pasted this XML at the end of this post)

Just run the solution to check if your Tree renders on the page with the checkboxes as well as the node elements.

The next step is to add the TreeView attribute.  In the code-behind, within the Page_Load event, add the following code:-

protected void Page_Load(object sender, EventArgs e)
    {
        TreeView1.Attributes.Add("onclick", "OnCheckBoxCheckChanged(event)");
    }

The next step is to add the Java Script function to handle the above:-

In the ASPX Page, within the <head> </head> tags, add the following code:-

<script type="text/javascript">
    function OnCheckBoxCheckChanged(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;
    }
</script>

The above code should work fine when you run and try selecting/de-selecting nodes and the parent behaviors etc.,

When I last checked, it works with IE8 Beta 2, Firefox 3.0.5 & Safari 3.2.1

The link for my original post View Entry

The ASP.NET Forum where this is being discussed with various options http://forums.asp.net/t/976122.aspx?PageIndex=1

The sample XML File content is here below:-

<?xml version="1.0" encoding="utf-8" ?>
<Syllabus>
    <Classes>
        <Class>XII Standard</Class>
        <Subjects>
            <Subject>Physics</Subject>
            <chapters>
                <chapter>Chapter 1</chapter>
                <Description>This is Chapter 1 in Physics</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 2</chapter>
                <Description>This is Chapter 2 in Physics</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 3</chapter>
                <Description>This is Chapter 3 in Physics</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 4</chapter>
                <Description>This is Chapter 4 in Physics</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 5</chapter>
                <Description>This is Chapter 5 in Physics</Description>
            </chapters>
        </Subjects>
        <Subjects>
            <Subject>Biology</Subject>
            <chapters>
                <chapter>Chapter 1</chapter>
                <Description>This is Chapter 1 in Biology</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 2</chapter>
                <Description>This is Chapter 2 in Biology</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 3</chapter>
                <Description>This is Chapter 3 in Biology</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 4</chapter>
                <Description>This is Chapter 4 in Biology</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 5</chapter>
                <Description>This is Chapter 5 in Biology</Description>
            </chapters>
        </Subjects>
        <Subjects>
            <Subject>Chemistry</Subject>
            <chapters>
                <chapter>Chapter 1</chapter>
                <Description>This is Chapter 1 in Chemistry</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 2</chapter>
                <Description>This is Chapter 2 in Chemistry</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 3</chapter>
                <Description>This is Chapter 3 in Chemistry</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 4</chapter>
                <Description>This is Chapter 4 in Chemistry</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 5</chapter>
                <Description>This is Chapter 5 in Chemistry</Description>
            </chapters>
        </Subjects>
        <Subjects>
            <Subject>Maths</Subject>
            <chapters>
                <chapter>Chapter 1</chapter>
                <Description>This is Chapter 1 in Maths</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 2</chapter>
                <Description>This is Chapter 2 in Maths</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 3</chapter>
                <Description>This is Chapter 3 in Maths</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 4</chapter>
                <Description>This is Chapter 4 in Maths</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 5</chapter>
                <Description>This is Chapter 5 in Maths</Description>
            </chapters>
        </Subjects>
    </Classes>
    <Classes>
        <Class>X Standard</Class>
        <Subjects>
            <Subject>Maths</Subject>
            <chapters>
                <chapter>Chapter 1</chapter>
                <Description>This is Chapter 1 in Maths</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 2</chapter>
                <Description>This is Chapter 2 in Maths</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 3</chapter>
                <Description>This is Chapter 3 in Maths</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 4</chapter>
                <Description>This is Chapter 4 in Maths</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 5</chapter>
                <Description>This is Chapter 5 in Maths</Description>
            </chapters>
        </Subjects>
        <Subjects>
            <Subject>Social</Subject>
            <chapters>
                <chapter>Chapter 1</chapter>
                <Description>This is Chapter 1 in Social</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 2</chapter>
                <Description>This is Chapter 2 in Social</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 3</chapter>
                <Description>This is Chapter 3 in Social</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 4</chapter>
                <Description>This is Chapter 4 in Social</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 5</chapter>
                <Description>This is Chapter 5 in Social</Description>
            </chapters>
        </Subjects>
        <Subjects>
            <Subject>Science</Subject>
            <chapters>
                <chapter>Chapter 1</chapter>
                <Description>This is Chapter 1 in Science</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 2</chapter>
                <Description>This is Chapter 2 in Science</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 3</chapter>
                <Description>This is Chapter 3 in Science</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 4</chapter>
                <Description>This is Chapter 4 in Science</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 5</chapter>
                <Description>This is Chapter 5 in Science</Description>
            </chapters>
        </Subjects>
        <Subjects>
            <Subject>English</Subject>
            <chapters>
                <chapter>Chapter 1</chapter>
                <Description>This is Chapter 1 in English</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 2</chapter>
                <Description>This is Chapter 2 in English</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 3</chapter>
                <Description>This is Chapter 3 in English</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 4</chapter>
                <Description>This is Chapter 4 in English</Description>
            </chapters>
            <chapters>
                <chapter>Chapter 5</chapter>
                <Description>This is Chapter 5 in English</Description>
            </chapters>

        </Subjects>
    </Classes>
</Syllabus>

Cheers !!!

posted @ Wednesday, January 21, 2009 1:22 PM

Print

Comments on this entry:

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Javed at 1/21/2009 8:53 PM
Gravatar
if Syllabus.xml was downloadable or example of the XML file would have made code bit easier to understand for beginners like me.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Crystal30 at 1/22/2009 11:12 AM
Gravatar
Thanks for this one. Very helpful :)

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by zabel at 1/26/2009 11:14 PM
Gravatar
Very helpful! Thanks a lot.
In the AreAllSiblingsChecked I had to add
a null-check. In the document was an empty table
and error occurs.
if (prevChkBox != null && !prevChkBox.checked) {
return false;

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Rahul Paliwal at 1/29/2009 4:59 PM
Gravatar
It was a great help, thanks buddy.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Nil at 2/19/2009 3:20 PM
Gravatar
Superb Solution!! Thanks a lot.. :)

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Hector Sanchez at 2/20/2009 8:50 PM
Gravatar
This solution was perfect, just was i looking for.

Thank you so much.!!!!!

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by James at 2/24/2009 1:10 AM
Gravatar
Works great on left click... how could I apply this to right click? I'm doing a check to make sure it's window.event.button==2 but the default right click menu still appears. Thanks for any help!

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Radhika at 3/2/2009 1:28 PM
Gravatar
Very useful. Thanks

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by terrgirl at 3/4/2009 4:42 PM
Gravatar
Perfect ! Thank you !

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Leo at 3/11/2009 12:35 PM
Gravatar
Thanks for the Post...
It helps a lot...

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Toby at 3/17/2009 12:22 AM
Gravatar
Exactly what I needed. Couldn't have asked for a better post.

Thank you.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Anthony at 3/21/2009 2:26 AM
Gravatar
You're the man! The best post I have seen in last 10 years. Wish you were taking donations, I would chip in.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by free multiline slots at 4/25/2009 3:40 PM
Gravatar
I have a Treeview control with checkboxes enabled inside a Ajax Update Panel.
On checking one or more node(s) and click of a button, the Required details are displayed in a Modal PopUp.
After the PopUp is closed, the Treeview checked nodes are not cleared, though
checked nodes are cleared - "myTree.ClearCheckedNodes();" on button click.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Ben Griswold at 4/29/2009 5:58 AM
Gravatar
Well, that's about the slickest piece of code I've come across in a while. I don't dare figure out how much time you just saved me.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by YP at 5/14/2009 2:26 PM
Gravatar
Thanks for the wonderful expamle

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Bpd at 5/16/2009 1:07 AM
Gravatar
awesome thanks!!!! Saved me lots of effort.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Walter Dellenback at 5/30/2009 8:51 AM
Gravatar
Excellent.. a truly excellent offering.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Manish at 6/26/2009 2:45 AM
Gravatar
Thanks, Its an perfect example.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by amper at 7/14/2009 4:33 AM
Gravatar
thank you so much ..^^

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Johnny at 7/14/2009 9:08 AM
Gravatar
Merci beaucoup, le code est excellent ! ^^

# Perfect!

Left by Mike at 7/29/2009 1:53 PM
Gravatar
Worked perfectly with almost no effort. I will also be able to extend with some other important functionality.

Thanks!

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by NateDogg at 8/6/2009 8:39 AM
Gravatar
Dude, in ten years of coding I don't think I have ever copied and pasted a script and had it work immediately. Outstanding job!

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Dev at 8/31/2009 6:23 AM
Gravatar
thanks.. worked like a charm...

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by vipin at 9/1/2009 4:55 AM
Gravatar
thank you so much .. Sir , You are great.......

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Eric at 9/3/2009 11:48 PM
Gravatar
Does not work if use CSS Friendly control?

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Ethiessen at 10/8/2009 7:09 AM
Gravatar
Thanks for the script! Works perfectly for my implementation.

Normally I don't like using JS when I don't have to, gets kinda messy, but in this case I couldn't find any other way to do it, and the script does exactly what I need.

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Postman at 10/8/2009 8:02 AM
Gravatar
Outstanding work! This is just what I needed. Now, do you have a good method for loading the tree from a database rather than an XML file?

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Foram at 10/14/2009 9:24 PM
Gravatar
Thanks A lot Great Article....

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Yeetender at 10/15/2009 2:12 PM
Gravatar
Thanks a lot , thats what exactly i wanted

# re: Updated: ASP.NET TreeView CheckBoxes – Check All – JavaScript

Left by Bashir Ahmed at 11/2/2009 3:44 AM
Gravatar
Good Work ;)

Your comment:



 (will not be displayed)


 
 
 
 
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345