Getting TreeNode values on the client side with javascript

Update: This blog has moved to http://pushpontech.blogspot.com

In a lot of scenarios it is required to get the value of a treenode (for an asp.net treeview) on the client side. While on the server we can get the nodevalue directly via the Value property of the Treenode, on the client it seems there is no corresponding attribute added to the anchor(yes treenodes are rendered as anchor(<a ..) tags) . Getting the node’s text is easy – just get hold of the node’s anchor element and call its innerText property. But how do we get the node value? Well, if you look closely at the rendered HTML for the node, you could find the node value lurking inside the href property for the node (provided you have not set the NavigateUrl property for the node manually). Something like:

href=”javascript:__doPostBack(‘TreeView1’,’sRoot\\firstChild\\…\\nodeValue‘)”

All we have to do is to extract that bold part from what the href property gives us.
Whereas there may be various scenarios where we may need the node value on the client, I would demonstrate it for the case of the node click itself – you want the value when you click a treenode. Try this:

1) Add an attribute to the treeview in code behind as:

if (!IsPostBack)
{
TreeView1.Attributes.Add(“onclick”, “return OnTreeClick(event)”);
}

2) Put the below code in head tag of .aspx page

<script type=”text/javascript”>
function OnTreeClick(evt)
{
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var nodeClick = src.tagName.toLowerCase() == “a”;
if(nodeClick)
{
var nodeText = src.innerText;
var nodeValue = GetNodeValue(src);
alert(“Text: “+nodeText + “,” + “Value: ” + nodeValue);
}
//return false; //uncomment this if you do not want postback on node click
}
function GetNodeValue(node)
{
//node value
var nodeValue = “”;
var nodePath = node.href.substring(node.href.indexOf(“,”)+2,node.href.length-2);
var nodeValues = nodePath.split(“\\”);
if(nodeValues.length > 1)
nodeValue = nodeValues[nodeValues.length – 1];
else
nodeValue = nodeValues[0].substr(1); return nodeValue;
}
</script>

Another scenario i can think of is when you have check boxes in the treeview and you want to get the nodevalue for the node that is checked. In that case you can just get the checkbox ( rendered as input tag) element first and then you can get the reference to the node via the nextSibling property for the checkbox.

That’s all. Hope this is helpful.

pushp


About this entry