zukanta zukanta - 2 months ago 33
Javascript Question

Disabling ASP.net treeview checkboxes

How would you guys conditionally disable checkboxes in an asp treeview?

For instance, if an application user does not have a certain permission, disable that permission entry checkbox in a permissions treeview.

Here's what i'm looking for, this is the equivaqlent in a winform app (the checkboxes are disabled where the text is grayed out):

enter image description here

I saw other solutions where the click event on the checkboxes is intercepted and ignored. I would prefer a solution where the checkboxes are simply set to disabled.

I'm looking for a C# solution but will be happy with a C#/Javascript solution.

Thanks!

Answer

Ok, found a fairly clean solution to this:

in code-behind:

TreeNode newNode = new TreeNode(permission.ToString());
newNode.SelectAction = TreeNodeSelectAction.None; // no Link

    if (shouldDisableCheckbox)
    {
        // Set a class so disabled nodes can be formatted thru CSS
        // and be identifiable as disabled in Javascript.
        newNode.Text = "<span class=disabledTreeviewNode>" + newNode.Text +"</span>";
    }

nodes.Add (newNode);

in Javascript, scan all treeview nodes for those that have that className and disable the checkboxes associated to them:

    // Called via a startup script created in Code Behind.
    // Disables all treeview checkboxes that have a text with a class=disabledTreeviewNode.
    // treeviewID is the ClientID of the treeView
    function DisableCheckBoxes(treeviewID)
    {
        TREEVIEW_ID = treeviewID;

        var treeView = document.getElementById(TREEVIEW_ID);

        if (treeView)
        {
            var childCheckBoxes = treeView.getElementsByTagName("input");
            for (var i = 0; i < childCheckBoxes.length; i++)
            {
                var textSpan = GetCheckBoxTextSpan(childCheckBoxes[i]);

                if (textSpan.firstChild)
                    if (textSpan.firstChild.className == "disabledTreeviewNode")
                        childCheckBoxes[i].disabled = true;
            }
        }
    }

function GetCheckBoxTextSpan(checkBox)
{
    // Set label text to node name
    var parentDiv = checkBox.parentNode;
    var nodeSpan = parentDiv.getElementsByTagName("span");

    return nodeSpan[0];
}
Comments