I have a web page on which I would like to display dynamically a tree based on a JSON array with the help of jQuery. Each node of my tree has a checkbox associated to it. When I click a node which has children, I would like all of them to be checked. I’ve already taken care of printing the tree and the checkboxes and I am now trying to select children nodes and I am not able.
Below is the code (simplified) that I have so far. Does anybody has an idea how I could automatically check the children checkboxes when a checkbox is checked with jQuery?
Thanks!
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var myJSON = {
"d": {
"__type": "Branch",
"Name": "$",
"FullPath": "$\\$",
"SubBranch": [
{
"__type": "Branch",
"Name": "System",
"FullPath": "$\\System",
"SubBranch": [
{
"__type": "Branch",
"Name": "Library",
"FullPath": "$\\System\\Library",
"SubBranch": [
]
},
{
"__type": "Branch",
"Name": "Configuration",
"FullPath": "$\\System\\Configuration",
"SubBranch": [
{
"__type": "Branch",
"Name": "Reimage",
"FullPath": "$\\System\\Configuration\\Reimage",
"SubBranch": [
]
},
{
"__type": "Branch",
"Name": "Installation",
"FullPath": "$\\System\\Configuration\\Installation",
"SubBranch": [
]
}
]
},
]
}
]
}
}
var output;
var indentationLevel = 0;
function GetSpacing(numberOfSpaces) {
var tabs = '';
for (i = 0; i < numberOfSpaces; i++) {
tabs += ' ';
}
return tabs;
}
function GetHtmlForFeaturePath(featurePath) {
return '<div>' + GetSpacing(indentationLevel) + '<input type="checkbox" id="' + featurePath.FullPath + '" class="featureTreeCheckbox" />' + featurePath.Name + "</div>";
}
function GetHtmlForFeaturePaths(node) {
output += GetHtmlForFeaturePath(node);
indentationLevel++;
jQuery.each(node.SubBranch, function() {
GetHtmlForFeaturePaths(this);
});
indentationLevel--;
}
String.prototype.startsWith = function(str) {
return this.match("^" + str) == str;
}
window.onload = function() {
GetHtmlForFeaturePaths(myJSON.d);
document.writeln(output);
/* How do I tell a node to check its children? */
$('input').click(function(event) {
var clickedControlId = this.id;
alert(clickedControlId);
/* alert($.grep(myJSON.d, function (a) { return a.FullPath == clickedControlId })); */
});
}
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
</body>
</html>