How to select a specific node programmatically? - jstree

I have a jstree. I want to select the node which is bound to the object which has a location with id of 158. This works but seems stupid. What's the more idiomatic way of doing this?
var $tree = $('.jstree', myContext),
node = $tree.find('li').filter(function() {
return ( $(this).data().location || {}).id === 158;
});
$tree.jstree('select_node', n)

Just wanted to chime in here as none of the answers worked for me. What finally DID work was very simple:
$('#someTree').jstree('select_node', 'someNodeId');
Note that I didn't initialize someNodeId as a jQuery object. It's just a plain string.
I did this right after a tree was loaded without putting it into a "ready" bind event as it seems to not be necessary.
Hope it saves some one from a few frustrating hours. . .
To hook into the tree after it has been loaded:
.on('loaded.jstree', function() {
// Do something here...
});

Based on jsTree groups you can try
jQuery("#getStartedTree").jstree("select_node", "#test2");
if the data looks like
The JSON in the TextFile.txt - borrowed from your simple example
[
{
"data" : "A node",
"children" : [ "Child 1", "Child 2" ]
},
{
"attr" : { "id" : "test1" },
"data" : {
"title" : "Long format demo",
"attr" : { "id" : "test2", "href" : "#" }
}
}
]
and jsTree set up
My tree container is <div id="getStartedTree">
My jsTree code
$("#getStartedTree").jstree({
"themes": {
"theme": "default",
"url": "../App_Css/Themes/Default/style.css",
"dots": true,
"icons": true
},
"json_data": {
"ajax": {
"url": "../SiteMaps/TextFile.txt",
"dataType": "json",
"data": function(n) {
return { id: n.attr ? n.attr("id") : 0 };
}
}
},
"plugins": ["themes", "json_data", "ui"]
});
Is that what you are after?

I did it with:
$('.jstree').jstree(true).select_node('element id');
this code:
jQuery.each(produto.categorias, function(i, categoria) {
$('#lista-categorias').jstree(true).select_node(categoria.dadoCategoria.id);
});

I was able to simulate a click on a jstree node as an alternative way to select a node.
The following code is what was used :
$(treeIdHandle + " li[id=" + nodeId + "] a").click();

If you're populating the tree using HTML instead of JSON data and wondering how to set the node_id, you just need to set the id attribute of the <li> element!
<div class="tree-menu">
<ul class="menu">
<li id="node_1">
Node 1 - Level 1
<ul class="menu">
<li id="node_3">
Node 3 - Level 2
</li>
</ul>
</li>
<li id="node_2">
Node 2 - Level 1
</li>
</ul>
</div>
Then
$('.tree-menu')
.jstree(true)
.select_node("node_3");
will select the Node 3 - Level 2 node.
For those getting javascript errors, remember to use Full version of jQuery, not the slim version!
For all down voters, here is the demo to prove it's working:
https://jsfiddle.net/davidliang2008/75v3fLbs/7/

i use jstree 3.0.8. don't use 'state'
'plugins' : ['dnd','sort','types','contextmenu','wholerow','ui']
and server offer the json, the selected node has
"state":{"selected":true,"opened":true}

This solution Works for me
// after the tree is loaded
$(".jstree").on("loaded.jstree", function(){
// don't use "#" for ID
$('.jstree').jstree(true).select_node('ElementId');
});
and even in a php loop (dynamically) :
$(".jstree").on("loaded.jstree", function(){
<?php foreach($tree as $node): ?>
$('.jstree').jstree(true).select_node('<?=$node?>');
<?php endforeach;?>
});
Hope this works for you.

i think u should write code to select node after jstree initialized, therefore use this code
$('#jstree')
.on('ready.jstree', function (e, data) {
// do function after jstree initialized
$('#jstree')
.jstree(true)
.select_node('nodeid');
});
hope its work :)

trigger click on first anchor
$("#jstree .jstree-anchor:first").click();
or by node id 158
$("#jstree #158").find(".jstree-anchor:first").click();
$('#' + 158).find(".jstree-anchor:first").click();

Related

Meteor App - 3 Rows from MongoDB is not displaying on Browser

What wrong with this code?
The 3 rows from mongoDB wont display on browser.
Please help.
My Short Meteor Code
Really cant find what's wrong.
<head>
<title>Things to do.</title>
</head>
<body>
<div class="container">
<header>
<h1>Our List</h1>
</header>
<ul>
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</div>
</body>
<template name="task">
<li>{{text}}</li>
</template>
Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
return Tasks.find({});
}
});
}
db.tasks.find()
2015-08-14T08:27:44.644+0000 trying reconnect to 127.0.0.1:8081 (127.0.0.1) failed
2015-08-14T08:27:44.644+0000 reconnect 127.0.0.1:8081 (127.0.0.1) ok
{ "_id" : ObjectId("55cd9d2456b678da6dcaa972"), "text" : "Hello world!", "createdAt" : ISODate("2015-08-14T07:47:48.586Z") }
{ "_id" : ObjectId("55cd9e2b56b678da6dcaa975"), "text" : "Eat out!", "createdAt" : ISODate("2015-08-14T07:52:11.635Z") }
{ "_id" : ObjectId("55cd9e3e56b678da6dcaa976"), "text" : "Tour around the world.", "createdAt" : ISODate("2015-08-14T07:52:30.944Z") }
There it is, my code in pure text.
A few things that could go wrong:
Your Tasks collection may not be published. Make sure you still have the autopublish package installed in your app, or publish and subscribe to your collection following this tutorial.
You are not using the same Mongodb database as your app's: make sure by printing the app's MONGO_URL.
In your js file:
if (Meteor.isServer) {
console.log(process.env.MONGO_URL);
}

jsTree - cannot create new node - all other functions work well

Deselect and hover funcntions work fina but create/delete/rename don't.
What do is do wrong?
info.json contains 5 nodes marked from 1 to 5.
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="jstree\dist\themes\default\style.min.css" />
<script src="jstree\dist\jstree.js"></script>
<script>
$(function() {
$('#test_tree').jstree({
'core' : {
'data' : {
'url' : 'info.json',
'data' : function (node) {
return { 'id' : node.id };
}
}
}
});
});
</script>
</head>
<body>
<div id="container" >
<div id="nav_bar">
<button id="create" onclick = "demo_create()">Create</button>
</div>
<div id="test_tree"></div
</div>
<script>
function demo_create() {
$.jstree.reference('#test_tree').hover_node('ajson5');
$.jstree.reference('#test_tree').deselect_node('ajson1');
$.jstree.reference('#test_tree').create_node();
};
</script>
</body>
I used same example from official site but it doesn't work
Thanks for any help.
First, in order for changes to be made to the tree, checkcallback in core config need to be set to true.
$('#test_tree').jstree({
'core' : {
'data' : {
'url' : 'info.json',
'data' : function (node) {
return { 'id' : node.id };
},
check_callback : true
}
}
You need to at least pass the parent.id to the create_node function.
$.jstree.reference('#test_tree').create_node('ajson1');
You could check the API at the jstree website for the full parameter list.
Demo jsTreeView 3.2.1 version
$("#treeView").jstree({ 'core': {
'check_callback': true,
'themes': {
"variant": "large"
},
'data':
[{"id":"1","parent":"#","text":"Parent Node"}]
}
});
You are missing the single quotation mark for the check_callback, after using that it will work. e.g. 'check_callback': true.
Code to create new Node
var ref_treeview = $("#treeView").jstree(true);
sel = ref_treeview.get_selected();
if (!sel.length) {
return false;
}
sel = sel[0];
sel = ref_treeview.create_node(sel, "childNode", "last", CreateNode,true);
Here CreateNode is my Callback function name
you have to send the selected element.
use the following (this is basically the code of the create button in the demo page http://www.jstree.com/demo/):
var tree = $("#test_tree").jstree(true);
var sel = tree.get_selected();
if (!sel.length)
{
return false;
}
sel = sel[0];
sel = tree.create_node(sel);
if (sel)
{
tree.edit(sel);
}
At the time when you create the jstree instance you just need to configure the
'core' setting as shown bellow:
$(function () {
$('#jstree').jstree({
'core':{check_callback : true}
});
You have to set the type of the newly created node like so:
$('#tree').jstree().create_node('#', {'id': 'blah', 'text': 'new node', 'type': 'folder'}, 'last', function() {
console.log('done');
});
jstree documentation should be improved.
using code from the other answers, I was able to make the following work:
Please note, this actually works. I am using it to create menus for an external ajax API.
function makeNode(menunode, menuname){
var inst = $.jstree.reference("#treemenu"); //get menu instance
var obj = inst.get_node(menunode);
inst.create_node(obj, menuname); //creates nodes. use "#" to make root nodes
inst.open_node(obj); // open the node (unfold)
});
usage:
//create menu instance and allow tree changes
$('#treemenu').jstree({'core' : {'check_callback': true}});
makeNode("#", "main menu"); //makes root node
makeNode("#j1_1", "submenu in main menu"); //makes sub node
this is assuming that you have a div with id="treemenu" thusly
<div id="treemenu"></div>

KendoUI: Unable to bind data to HTML elements from JSON file.

I am new to kendo ui and mvvm, and I'm facing this issue:
I'm having a JSON file in the follow format:
[
{
"Id":1,
"img":"shoes.png"},
{"Id":2,
"img":"books.png"}
}
]
I am reading the file using the sample mentioned online by kendo guys as follows:
var crudServiceBaseUrl = "pro.json";
var viewModel = kendo.observable({
productsSource: new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl,
dataType: "json"
},
update: {
url: crudServiceBaseUrl,
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl,
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
return options;
}
},
batch: true,
schema: {
model: {
id: "Id"
}
}
})
});
kendo.bind($("#form-container"), viewModel);
I am able to bind the data from the data source to a Kendo Control such as a dropdownlist or some other Kendo Control. But when I try binding the data to an HTML Control (mostly an img tag). It stops working and gives an error saying "this.parent" is not a function.
following is the HTML which works:
Select Product: <select data-role="dropdownlist" data-value-field="Id" data-text-field="img"
data-bind="source: productsSource"></select>
However binding to a normal <img> tag does not work. In short I need to bind images based on src value to a div using kendo ui mvvm.
Kindly help me out. Thanks!!
-
Hardik
Currently Kendo MVVM cannot bind a data source to an HTML element. Only Kendo UI widgets can be bound to a kendo.data.DataSource. Using a widget e.g. the ListView would work for a DIV:
<div data-role="listview"
data-template="template"
data-bind="source: productsSource">
</div>
<script id="template" type="text/x-kendo-template">
<img data-bind="attr: { src: img }" />
</script>

How to use Template in rowexpander plugin - Ext JS 4

Can we use template as follows:
plugins: [{
ptype: 'rowexpander',
selectRowOnExpand : false,
rowBodyTpl: new Ext.XTemplate(
'<p>Qusetions: {question}</p><p>',
'<tpl for="option">',
'<p>{option[0]}</p>',
'</tpl></p>'
)
}]
I am unable to see anything. I have this JSON:
{
"total": 2,
"data": [
{
"qno":1,
"question":"What's Your Fav color",
"option":['red','green','blue']
},
{
"qno":2,
"question":"What's Your coom color",
"option":['yellow','red','green','blue']
}
]
}
Model File
Ext.define('AM.model.Question', {
extend: 'Ext.data.Model',
fields: [
{name: 'question'},
{name: 'option'},
{name: 'images'},
{name: 'qno'}
]});
I want to see the output as follows:
+ Questions: What is your fav color
<radiobutton> Red
<radiobutton> Green
<radiobutton> Blue
Am using Ext JS 4.1 version
Thanks in advance for your answers
When iterating through an array using XTemplate, the current item is referred to using {.}. Your template should look something like this:
'<p>Questions: {question}</p>',
'<p>',
'<tpl for="option">',
'<p>{.}</p>',
'</tpl>',
'</p>'
However, it gets a little more tricky if you want to do a radio group. XTemplate provides the parent property to access objects outside of the current context. So instead of a <p> tag in the middle, your radio group might look like this:
'<tpl for="option">',
'<input type="radio" name="qno_{parent.qno}" value="{.}" />{.}<br/>'
'</tpl>'

jquery ui autocomplete js error on keydown

i've included the jquery ui automcomplete plugin into the following structure:
<li class="search">
<input type="text" class="searchfield" name="searchfield" value="Search for Products" />
</li>
my javascript for this input field looks like:
<script type="text/javascript">
function addSearchFieldFunctionality() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$('.searchfield').each(function () {
$(this).autocomplete({
source: availableTags,
minLength: 1
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
var a = $('<a>', {
href: item.value,
text: item.label,
"class" : "mySearchClass"
});
var b = $('<a>', {
href: item.value,
text: "Add", style: "float:right"});
var $li = $('<li></li>', {style:"width:100%"});
return $li.add(a).appendTo(ul);
};
});
}
</script>
I'm loading that function on document ready. for some reason, if a start typing e.g. the first three letters of a item, i get a resultlist. as soon as i push the keydown push button on the keyword, i get the following error in the chrome (latest version) console:
Uncaught TypeError: Cannot read property 'top' of null
a.widget.activate jquery-ui.min.js:12
a.widget.move jquery-ui.min.js:12
a.widget.next jquery-ui.min.js:12
a.widget._move jquery-ui.min.js:12
a.widget._create.element.addClass.attr.attr.bind.bind.d jquery-ui.min.js:12
f.event.dispatch jquery-1.7.1.min.js:3
f.event.add.h.handle.i
i'm using version 1.7.1 of jQuery and Version 1.8.12 of jquery UI
On the demo page of jquery ui autocomplete the keydown works well.
Any ideas what's going wrong with my constellation?
It doesn't make a difference to use remote or local data.
Best regards,
Ramo
I really can make your code working. So I tried to rewrote it in a more simplier way. The problem is render functions only accept strings, not html element. So I add a listener to render the list after its generation (fired on keydown() event).
My thought is you are doing it the wrong way.
why adding another class on those items ? they have already one, so they can be styled.
why transforming them into a nodes ? just add a click() event on them
Could you explain your functional goal ?
// Your list of links
var redirectLinks = {'Ruby': '1234.com', 'Asp': '1235.com'};
function redirect(url) {
// TODO implement window.location=url or whatever you like
if(redirectLinks[url] != undefined) {
alert('redirecting to '+url+' => '+redirectLinks[url]);
}
}
$('.searchfield').each(function () {
$(this).autocomplete(availableTags, {
minLength: 1,
change: function(event, ui) {
console.log('this change event doesnt seem to be fired');
},
select: function(event, ui) {
console.log('this select event doesnt seem to be fired');
}
});
// After the list construction
$(this).keyup(function(e){
if (e.which == 13) { // typing enter validates the input => autocompletechange
console.log('validating input '+$(this).val());
redirect($(this).val());
}
var $list = $('.ac_results:first ul').find('li');
$list.click(function() { // adding an event on suggestion => autocompleteselect
console.log('clicking on suggestion '+$(this).text());
redirect($(this).text());
});
});
});