I'm using jsTree to show a tree with checkboxes. Each level of nodes is loaded on-demand using the json_data plugin.
If a node's descendent is checked, then that node should be in an "undetermined state" (like ACME and USA).
The problem is, the tree starts out collapsed. ACME looks unchecked but should be undetermined. When I finally expand to a checked node, jsTree realizes the ancestors should be undetermined.
So I need to be able to put a checkbox in the undetermined state without loading its children.
With jsTree you can pre-check a box by adding the jstree-checked class to the <li>. I tried adding the jstree-undetermined class, but it doesn't work. It just puts them in a checked state.
Here's my code:
$("#tree").jstree({
plugins: ["json_data", "checkbox"],
json_data: {
ajax: {
url: '/api/group/node',
success: function (groups) {
var nodes = [];
for (var i=0; i<groups.length; i++) {
var group = groups[i];
var cssClass = "";
if(group.isSelected)
cssClass = "jstree-checked";
else if(group.isDecendantSelected)
cssClass = "jstree-undetermined";
nodes.push({
data: group.name,
attr: { 'class': cssClass }
});
}
return nodes;
}
}
}
})
My Question
How do I set a node to the undetermined state?
I had the same problem and the solution I found was this one:
var tree = $("#tree").jstree({
plugins: ["json_data", "checkbox"],
json_data: {
ajax: {
url: '/api/group/node',
success: function(groups) {
var nodes = [];
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
var checkedState = "false";
if (group.isSelected)
checkedState = "true";
else if (group.isDecendantSelected)
checkedState = "undetermined";
nodes.push({
data: group.name,
attr: { 'checkedNode': checkedState }
});
}
return nodes;
},
complete: function () {
$('li[checkedNode="undetermined"]', tree).each(function () {
$(this).removeClass('jstree-unchecked').removeClass('jstree-checked').addClass('jstree-undetermined');
});
$('li[checkedNode="true"]', tree).each(function () {
$(this).removeClass('jstree-unchecked').removeClass('jstree-undetermined').addClass('jstree-checked');
});
$('li[checkedNode="false"]', tree).each(function () {
$(this).removeClass('jstree-checked').removeClass('jstree-undetermined').addClass('jstree-unchecked');
});
}
}
}
});
Hope it helps you!
Maybe this changed in the meanwhile...
But now (version 3.0.0) the really simple solution works:
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
undetermined : boolean // is the node undetermined <<==== HERE: JUST SET THIS
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
Learned directly from the source code at: https://github.com/vakata/jstree/blob/6507d5d71272bc754eb1d198e4a0317725d771af/src/jstree.checkbox.js#L318
Thank you guys, and I found an additional trick which makes life a little better, but it requires a code change in jstree.js. Looks like an oversight:
Look at the get_undetermined function, and scan for the keyword break. That break should be a continue.
If you make that one change, then all you need to do is provide the state (for the main object and its children), and jstree will automatically take care of cascading upwards for undetermined state. It was bailing out early from the scripting and failing to catch all the undetermined nodes properly, requiring the above ugly workarounds for styling and such.
Here's my config (no special attrs or complete() function required) using AJAX:
var tree = $('#jstree').jstree({
"core": {
"themes": {
"variant": "large"
},
'data': {
'url': function (node) {
return "{{API}}/" + node.id + "?product_id={{Product.ID}}"
},
'dataType': 'json',
'type': 'GET',
'success': function (data) {
if (data.length == 0) {
data = rootStub
}
return {
'id': data.id,
'text': data.text,
'children': data.children,
'state': data.state,
}
}
}
},
"checkbox": {
// "keep_selected_style": false,
"three_state": false,
"cascade": "undetermined"
},
"plugins": ["wholerow", "checkbox"],
});
Related
I'm using get_bottom_selected to get all the checked/selected nodes in JSTree. When I setup a button in my form that calls the following method it works. When I try to call the same function from check box click event it does not find any selected nodes, even if there are some.
function testit() {
var data = $('#my_tree').jstree(true).get_bottom_selected(true);
for(var count = 0; count < data.length; count++){
// Do Stuff
}
}
When the following event fires I want to call the function and get all the selected child nodes, but it does not work. Is there something specific to do on this event that works different than calling from a button click event?
.on("check_node.jstree uncheck_node.jstree", function(e, data) {
testit(); // first line of this function does not get any selected data, even if several are selected. When called from a button click event in my form it does work.
});
Here's how I currently have my jstree setup.
$('#my_tree')
.on("changed.jstree", function (e, data) {
// Do Stuff
})
.jstree({
checkbox: {
"keep_selected_style": false,
"visible" : true,
"three_state": true,
"whole_node" : true,
},
plugins: ['checkbox'],
'core' : {
'multiple' : true,
'data' : {
"url" : "/static/content_data.json",
"dataType" : "json"
}
}
})
.on("check_node.jstree uncheck_node.jstree", function(e, data) {
testit();
});
Because of the strict mode you will get the exception that if you try to use get_bottom_checked
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them.
at Function.invokeGetter (<anonymous>:2:14)
You can use data.selected from your check or uncheck event handler if you just want the ids of selected nodes but if you need more than that you can use 'data.instance._model.data'. As you can see in my example I am trying to alert if there is only one item selected and that's state is open. In the code example, you can see the Alert if you open the `Europe1 and select the checkbox.
var data1 = [{
"id": "W",
"text": "World",
"state": {
"opened": true
},
"children": [{
"text": "Asia"
},
{
"text": "Africa"
},
{
"text": "Europe",
"state": {
"opened": false
},
"children": ["France", "Germany", "UK"]
}
]
}];
function testit(data) {
alert(data.length + ' and ids are ' +data );
for (var count = 0; count < data.length; count++) {
}
}
$('#Tree').jstree({
core: {
data: data1,
check_callback: false
},
checkbox: {
three_state: false, // to avoid that fact that checking a node also check others
whole_node: false, // to avoid checking the box just clicking the node
tie_selection: false // for checking without selecting and selecting without checking
},
plugins: ['checkbox']
})
$('#Tree').on("check_node.jstree uncheck_node.jstree", function(e, data) {
if (data.selected.length === 1) { alert(data.instance._model.data[data.selected].state['opened']); }
testit(data.selected);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="Tree"></div>
According to this
you can get all selected nodes on change event like this:
$('#jstree').on('changed.jstree', function (e, data) {
var i, j, r = [];
for(i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).text);
}
$('#event_result').html('Selected: ' + r.join(', '));
}).jstree();
I have set up my fancytree to open via lazy loading, and it works very nicely.
$("#tree").fancytree({
selectMode: 1, quicksearch:true, minExpandLevel:2,
autoScroll: true,
source: [{
title: "Root",
key: "1",
lazy: true,
folder: true
}],
lazyLoad: function(event, data) {
var node = data.node;
data.result = {
url: "getTreeData.jsp?parent=" + node.key,
data: {
mode: "children",
parent: node.key
},
cache: false
};
}
});
However, if a user has previously selected a point on the tree, I would like the tree to open to that point.
I have a variable called hierarchy which looks like "1/5/10/11/200" and holds the sequence of keys to that certain point.
The following will not work:
$("#tree").fancytree("getTree").getNodeByKey("1").setExpanded();
$("#tree").fancytree("getTree").getNodeByKey("5").setExpanded();
$("#tree").fancytree("getTree").getNodeByKey("10").setExpanded();
$("#tree").fancytree("getTree").getNodeByKey("11").setExpanded();
$("#tree").fancytree("getTree").getNodeByKey("200").setExpanded();
The reason why it will not work, apparently, is because there needs to be some delay between one statement and the next.
The following code works, however it is in my mind messy:
function openNode(item) {
$("#tree").fancytree("getTree").getNodeByKey(String(item)).setExpanded();
}
function expandTree(hierarchy) {
var i=0;
hierarchy.split("/").forEach(function (item) {
if (item!="") {
i++;
window.setTimeout(openNode, i*100,item);
}
});
Is there any neater way of opening to a specific point on the tree?
The following code seems to do the trick.
It was adapted from
http://wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree.html#loadKeyPath
function expandTree(hierarchy) {
$('#tree').fancytree("getTree").loadKeyPath(hierarchy).progress(function(data) {
if (data.status === "loaded") {
console.log("loaded intermediate node " + data.node);
$('#tree').fancytree("getTree").activateKey(data.node.key);
} else if (data.status === "ok") {}
}).done(function() {});
}
I have a simple grid with the following options:
jQuery("#mygrid").jqGrid({
url: 'dataurl.htm',
datatype: 'json',
ajaxSelectOptions: { cache: false }
...
colModel: [
{ name: 'foo', index: 'foo', width: 25, stype: 'select', searchoptions:{ sopt:
['eq'], dataUrl: 'someurl.htm?columnName=foo'}}
]
});
However, when I call $("#mygrid").trigger("reloadGrid"); it only loads the data for the table from dataurl.htm but it does not load the data for the foo column from the some url.htm link.
I've read couple of questions like these on SO and it was suggested to have ajaxSelectOptions: { cache: false } but this is not working for me.
The someurl.htm returns <select> <option val=''>something</option></select>
It's absolutely correct question! The current implementation of jqGrid has only toggleToolbar method which can hide the toolbar, but the toolbar itself will be created once. So all properties of the toolbar stay unchanged the whole time.
To fix the problem I wrote small additional method destroyFilterToolbar which is pretty simple:
$.jgrid.extend({
destroyFilterToolbar: function () {
"use strict";
return this.each(function () {
if (!this.ftoolbar) {
return;
}
this.triggerToolbar = null;
this.clearToolbar = null;
this.toggleToolbar = null;
this.ftoolbar = false;
$(this.grid.hDiv).find("table thead tr.ui-search-toolbar").remove();
});
}
});
The demo uses the method. One can recreate searching toolbar after changing of properties of some columns. In the code below one can change the language of some texts from the searching toolbar:
The corresponding code is below:
$("#recreateSearchingToolbar").change(function () {
var language = $(this).val();
// destroy searching toolbar
$grid.jqGrid("destroyFilterToolbar");
// set some searching options
$grid.jqGrid("setColProp", "closed",
language === "de" ?
{searchoptions: {value: ":Beliebig;true:Ja;false:Nein"}} :
{searchoptions: {value: ":Any;true:Yes;false:No"}});
$grid.jqGrid("setColProp", "ship_via",
language === "de" ?
{searchoptions: {value: ":Beliebig;FE:FedEx;TN:TNT;IN:Intim"}} :
{searchoptions: {value: ":Any;FE:FedEx;TN:TNT;IN:Intim"}});
// create new searching toolbar with nes options
$grid.jqGrid("filterToolbar", {stringResult: true, defaultSearch: "cn"});
});
I'm trying to capture the name of the newly created node with jstree's contextmenu. I can capture the name of the parent node that I'm adding the new node under (with obj.text()), however, what I really need is the name of the newly created node.
So, somehow, there needs to be an "onChange" event that can be called within jstree contextmenu that fires once the user hits enter on that newly created node?
Any ideas? I've enclosed the contextmenu code:
}).jstree({
json_data: {
data: RBSTreeModel,
ajax: {
type: "POST",
data: function (n) {
return {
NodeID: n.attr("id").substring(4),
Level: n.attr("name").substring(7)
};
},
url: function (node) {
return "/Audit/GetRequirementsTreeStructure";
},
success: function (new_data) {
return new_data;
}
}
},
contextmenu: {
items: function($node) {
return {
createItem : {
"label" : "Create New Branch",
"action" : function(obj) { this.create(obj); alert(obj.text())},
"_class" : "class"
},
renameItem : {
"label" : "Rename Branch",
"action" : function(obj) { this.rename(obj);}
},
deleteItem : {
"label" : "Remove Branch",
"action" : function(obj) { this.remove(obj); }
}
};
}
},
plugins: ["themes", "json_data", "ui", "crrm", "contextmenu"]
});
You can bind to the "create.jstree" event, which will fire after a node is created. In the callback of that event, you will have access to the newly created node and can rollback/revert the create node action if you choose. The documentation for it is lacking, but there is an example on the demo page. Here is another example that came from my code:
}).jstree({... You jstree setup code...})
.bind("create.jstree", function(e, data) {
// use your dev tools to examine the data object
// It is packed with lots of useful info
// data.rslt is your new node
if (data.rslt.parent == -1) {
alert("Can not create new root directory");
// Rollback/delete the newly created node
$.jstree.rollback(data.rlbk);
return;
}
if (!FileNameIsValid(data.rslt.name)) {
alert("Invalid file name");
// Rollback/delete the newly created node
$.jstree.rollback(data.rlbk);
return;
}
.. Your code etc...
})
Based on Bojin Li's answer, it seems that the latest version of jsTree uses the event "create_node" instead of "create":
}).jstree({... You jstree setup code...})
.bind("create_node.jstree", function(e, data) {
...
});
I'm new to ember, so maybe I'm doing this wrong.
I'm trying to create a select dropdown, populated with three values supplied from an external datasource. I'd also like to have the correct value in the list selected based on the value stored in a different model.
Most of the examples I've seen deal with a staticly defined dropdown. So far what I have is:
{{#view contentBinding="App.formValues.propertyType" valueBinding="App.property.content.propertyType" tagName="select"}}
{{#each content}}
<option {{bindAttr value="value"}}>{{label}}</option>
{{/each}}
{{/view}}
And in my module:
App.formValues = {};
App.formValues.propertyType = Ember.ArrayProxy.create({
content: [
Ember.Object.create({"label":"App","value":"app", "selected": true}),
Ember.Object.create({"label":"Website","value":"website", "selected": false}),
Ember.Object.create({"label":"Mobile","value":"mobile", "selected": false})
]
});
And finally my object:
App.Property = Ember.Object.extend({
propertyType: "app"
});
App.property = Ember.Object.create({
content: App.Property.create(),
load: function(id) {
...here be AJAX
}
});
The dropdown will populate, but it's selected state won't reflect value of the App.property. I know I'm missing some pieces, and I need someone to just tell me what direction I should go in.
The answer was in using .observes() on the formValues. For some reason .property() would toss an error but .observes() wouldn't.
I've posted the full AJAX solution here for reference and will update it with any further developments.
App.formValues = {};
App.formValues.propertyType = Ember.ArrayProxy.create({
content: [],
load: function() {
var that = this;
$.ajax({
url: "/api/form/propertytype",
dataType: "json",
success: function(data) {
that.set("content", []);
_.each(data, function(item) {
var optionValue = Ember.Object.create(item);
optionValue.set("selected", false);
that.pushObject(optionValue);
});
that.update();
}
});
},
update: function() {
var content = this.get("content");
content.forEach(function(item) {
item.set("selected", (item.get("value") == App.property.content.propertyType));
});
}.observes("App.property.content.propertyType")
});
App.formValues.propertyType.load();