Tuesday, May 12, 2009

Select parents in a TreeView using JQuery

The requirement is to be able to select the parents of a node in a TreeView if a child is selected. Not only the first parent, all parents and to be able to unselect after if we want.

If we look at generated source code we will notice that the parent node is in a div tag. Inside this div are the childrens inside a table/tr/td tags. So we must look for checkboxes inside a table data, table that is nested into a div. Is better to assign an attribute to the tree to be more easy to find. I added  the attribute “cipg” with the value “mpower”. The id of the tree is “theOne”.

The code below solve this requirement. I’m sure this can be improved.

<script type="text/javascript"> 

function applyToParent(parent, treeId)
{
var actualId = treeId+'theOne';
if (parent.attr('id')!= actualId)
{
var parentId = parent.attr('id').replace('Nodes', '');
var theOne = $("div[cipg='mpower'] table tr td input[type='checkbox'][id^='"+parentId+"']");
theOne.attr('checked', true);
applyToParent(GetParent(theOne), treeId);
}
}

function GetParent(theCurrent)
{
return theCurrent.parent().parent().parent().parent().parent();
}

function checkTheParent()
{
if($(this).attr('checked') == true)
{
var theParent = GetParent($(this));
var currentId = $(this).attr('id');
var treeId = currentId.substring(0,currentId.indexOf('theOne'));
applyToParent(theParent, treeId);
}
}

$(document).ready(function(){
$("div[cipg='mpower'] table tr td input[type='checkbox']").bind('click', checkTheParent);
});

</script>

1 comment: