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

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>

Related

Bootstrap-vue modal manipulate ok-disabled state in function

I've set the default OK Button in a Bootstrap-Vue Modal to disabled true and want to change it when inputing something in ab-form-input. Calling the function works but disabling ok-disabled not. Can't get access to the property. Seems to be a very basic question but in the component docs in bootstrap-vue there is only the infor that state can be changed (true-false) but not how to manipulate via script.
`
<template>
<b-modal
id="component-modal"
title="Add Component"
#ok="handleOk"
:ok-disabled="true"
>
<div class="container">
<b-row>
<b-col>Component: </b-col>
<b-col>
<b-form-input
v-model="component"
id="new-component"
required
#input="enableOK"
></b-form-input>
</b-col>
</b-row>
</div>
</b-modal>
</template>
<script>
import axios from 'axios';
import store from '../../store';
export default {
data() {
return {
count: 0,
};
},
methods: {
handleOk() {
this.handleSubmit();
},
handleSubmit() {
this.insertComponentClass(this.component, store.state.project);
delete this.component;
},
insertComponentClass(componentClass, pid) {
const path = `${store.state.apiURL}/componentclass/add`;
const payload = {
name: componentClass,
project_id: pid,
};
axios
.put(path, payload)
.then(() => {
this.$parent.getComponents();
})
.catch((error) => {
console.error(error);
});
},
enableOK() {
console.info('enable ok fired');
this.ok-disable = false; // doesnt wor, linter says "Invalid left-hand side in assignment expression"
},
},
};
</script>
`
There's a few things going on here that are incorrect.
You're binding the ok-disabled prop to a hardcoded value of true in your template. If you want that value to change, you'll need to bind it to a variable that you can update in your components <script>
For example, you can update the modal's :ok-disabled prop to:
:ok-disabled="okDisabled"
Then in your <script> data function, add it to the return object (defaulted to true):
data() {
return {
count: 0,
okDisabled: true,
}
}
Now the modal's :ok-disabled property is bound to that variable and we can change the value in the enableOk method like so:
this.okDisabled = false;
Note regarding the lint error, the name of the variable you're trying to assign to this.ok-disable is not a valid variable name. You can't use a dash (-) character for a Javascript variable name. You can rename it to the property we created earlier this.okDisabled

Ember could not get select value from template to component

I'm struggling with this. I would like to pass a select value from template to component.
Here is my template
<select name="bank" class="form-control" id="sel1" onchange={{action "updateValue" value="bank"}}>
{{#each banks as |bank|}}
<option value={{bank.id}}>{{bank.name}}</option>
{{/each}}
{{log bank.id}}
</select>
And here is my component
import Ember from 'ember';
export default Ember.Component.extend({
store: Ember.inject.service('store'),
banks: Ember.computed(function() {
return this.get('store').findAll('bank');
}),
didUpdate() {
const banques = this.get('banks');
const hash = [];
banques.forEach(function(banque) {
hash.push(banque.get('name'));
});
Ember.$(".typeahead_2").typeahead({ source: hash });
},
actions: {
expand: function() {
Ember.$('.custom-hide').attr('style', 'display: block');
Ember.$('.custom-display').attr('style', 'display: none');
},
updateValue(selectedValue) {
this.set('bank.id', selectedValue);
},
login() {
console.log(this.get('bank.id'));
}
}
});
And i've got this beautiful error : Property set failed: object in path "bank" could not be found or was destroyed.
Any idea ? Thanks
When you use value attribute then you need to specify correct property name to be retrieved from the first argument(event). in your case you just mentioned bank - which was not found in event object. that's the reason for that error.
onchange={{action "updateValue" value="target.value"}}
inside component
updateValue(selectedValue) {
this.set('bank.id', selectedValue);
},

How to add "select" in dojo tooltipdialog content programmatically?

I want to display dojo select inside a dijit/TooltipDialog. The items of the dojo select are dynamically loaded. So I want to add this select programmaticaly. The content of TooltipDialog can be an object but select needs a domNode to be held. The code is :
<head>
<script>
require([
"dojo/parser",
"dijit/form/Select",
"dijit/TooltipDialog",
"dojo/on",
"dojo/dom",
"dojo/_base/lang",
"dijit/popup",
"dojo/data/ObjectStore",
"dojo/store/Memory",
"dojo/domReady!"
], function(parser,Select,TooltipDialog,on,dom,lang,popup, ObjectStore, Memory){
parser.parse();
var t={mySel:null};
var store = new Memory({
data: [
{ id: "foo", label: "Foo" },
{ id: "bar", label: "Bar" }
]
});
var os = new ObjectStore({ objectStore: store });
t.mySel = new Select({
store: os
}, "ttt");
var myTooltipDialog = new TooltipDialog({
content: t,
onMouseLeave: function(){
popup.close(myTooltipDialog);
}
});
on(dom.byId("mmm"),"mouseover" ,lang.hitch(this,function(e){
popup.open({
popup: myTooltipDialog,
orient: ["above-centered","above","below"],
around:dom.byId('mmm')
});
t.mySel.startup();
}));
t.mySel.on("change", function(){
console.log("my value: ", this.get("value"))
})
})
</script>
</head>
<body class="claro">
<div id="ttt" > tttt</div><br>
<div id="mmm" > tttt</div><br>
</body>
You are assignign an object t the tooltip content not a domenode
so try to make these change :
var myTooltipDialog = new TooltipDialog({
content: t.mySel.domNode,
onMouseLeave: function() {
popup.close(myTooltipDialog);
}
}

Auto complete with multiple keywords

I want . Auto complete text box with multiple keyword. it's from database. if I use jQuery and do operation in client side mean. If the database size is huge, it leads to some issues. I need to know how this is done on the server side and get proper result.
I have already seen this topic but the operation is done on the client side. I need it from the database directly.
<html>
<head>
<title>Testing</title>
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.srchHilite { background: yellow; }
</style>
<script src="scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
NewAuto();
});
function NewAuto() {
var availableTags = ["win the day", "win the heart of", "win the heart of someone"];
alert(availableTags); // alert = win the day,win the heart of,win the heart of someone
$("#tags").autocomplete({
source: function(requestObj, responseFunc) {
var matchArry = availableTags.slice(); // Copy the array
var srchTerms = $.trim(requestObj.term).split(/\s+/);
// For each search term, remove non-matches.
$.each(srchTerms, function(J, term) {
var regX = new RegExp(term, "i");
matchArry = $.map(matchArry, function(item) {
return regX.test(item) ? item : null;
});
});
// Return the match results.
responseFunc(matchArry);
},
open: function(event, ui) {
// This function provides no hooks to the results list, so we have to trust the selector, for now.
var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
var srchTerm = $.trim($("#tags").val()).split(/\s+/).join('|');
// Loop through the results list and highlight the terms.
resultsList.each(function() {
var jThis = $(this);
var regX = new RegExp('(' + srchTerm + ')', "ig");
var oldTxt = jThis.text();
jThis.html(oldTxt.replace(regX, '<span class="srchHilite">$1</span>'));
});
}
});
}
</script>
</head>
<body>
<div>
<label for="tags">
Multi-word search:
</label>
<input type="text" id="tags" />
</div>
</body>
</html>
take a look to Select2 it may help you.
Select2 is a jQuery based replacement for select boxes. It supports
searching, remote data sets, and infinite scrolling of results.
link
In your code, you have provided source as array. As you mentioned in comments, problem is how to get the data to source in jquery.
To make this work,
You need to do following
load jquery in header, which is you have already done.
Provid array,string or function for the source tag. [See api for
the source tag][1]
[1]: http://api.jqueryui.com/autocomplete/#option-source
In your serverside script, provid Jason encoded string.
If you check the API, you can see they have clear mentioned this.
Here is the jquery code
$(function() {
$( "#option_val" ).autocomplete({
dataType: "json",
source: 'search.php',
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
Here is the php code, Sorry if you use differnt serverside script language.
<?php
// Create connection
$con=mysqli_connect("localhost","wordpress","password","wordpress");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result=mysqli_query($con,"select * from wp_users");
while($row = mysqli_fetch_array($result))
{
$results[] = array('label' => $row['user_login']);
}
echo json_encode($results);
mysqli_close($con);
?>

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());
});
});
});