I have a ajax request returning data to show a tree with checkboxes. In de html data returned from the ajax call the check state of the items is defined using a custom data-checkstate attribute. How can i restore this check state in the tree?
Expected result:
<head>
<meta charset="utf-8" />
<title>JsTree test</title>
<link rel="stylesheet" href="http://static.jstree.com/latest/assets/dist/themes/default/style.min.css" />
<script src="http://static.jstree.com/latest/assets/dist/libs/jquery.js"></script>
<script src="http://static.jstree.com/latest/assets/dist/jstree.min.js"></script>
</head>
<body>
<div id="container"/>
</body>
</html>
<script>
$(function () {
var ajaxResponse =
'<ul> <li data-checkstate="undetermined">Parent 1' +
' <ul>' +
' <li data-checkstate="unchecked">Child 1a' +
' <ul>' +
' <li data-checkstate="unchecked">Grantchild 1a1</li>' +
' <li data-checkstate="unchecked">Grantchild 1a2</li>' +
' </ul>' +
' </li>' +
' <li data-checkstate="undetermined">Child 1b' +
' <ul>' +
' <li data-checkstate="unchecked">Grantchild 1b1</li>' +
' <li data-checkstate="checked">Grantchild 1b2</li>' +
' </ul>' +
' </li>' +
' </ul>' +
'</li>' +
'<li data-checkstate="unchecked">Parent 2' +
' <ul>' +
' <li data-checkstate="unchecked">Child 2a' +
' <ul>' +
' <li data-checkstate="unchecked">Grantchild 2a1</li>' +
' <li data-checkstate="unchecked">Grantchild 2a2</li>' +
' </ul>' +
' </li>' +
' <li data-checkstate="unchecked">Child 1b' +
' <ul>' +
' <li data-checkstate="unchecked">Grantchild 2b1</li>' +
' <li data-checkstate="unchecked">Grantchild 2b2</li>' +
' </ul>' +
' </li>' +
' </ul>' +
'</li> </ul>';
var tree = $("#container");
tree.html(ajaxResponse);
tree.on('loaded.jstree', function () {
// restore tree state
$('li[data-checkstate="checked"]').each(function () {
$(this).addClass('jstree-checked');
});
$('li[data-checkstate="undetermined"]').each(function () {
$(this).addClass('jstree-undetermined');
});
});
tree.jstree({
plugins: ["checkbox"],
core: {
"themes": {
"icons": false
}
}
});
});
</script>
Update: Edit: Moved to the answer
I know this is old but might be helpfull for someone.
To check the checkbox on load via HTML, set the class like in example:
<li id="123">
<a href="#" class="jstree-clicked">Click me</a>
</li>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With