Store Result of Renamed JS.Tree Node - javascript

I have an editable tree structure. A user can create, rename and delete individual nodes. Right now, when I choose a node to rename, I store the original value in a variable using this code.
function rename() {
var data = null;
data = $(plBox2).jstree().get_selected(true)[0].text;
console.log(data);
}
This function is called when when "Rename" is selected in the context menu. What I want to do is store the new value of that node after it is renamed but I cannot figure it out. My ultimate goal is to send both the old value and the new value to a MySQL table.
Here is my tree and context menu:
$('#plBox2').jstree({
"checkbox": {
"keep_selected_style": false
},
"core" : {
"themes": {
"name": "default",
"dots": true,
"icons": true,
},
"check_callback": true,
},
"plugins" : [
"massload", "wholerow", "contextmenu", "changed", "sort", "dnd",
],
"contextmenu":{
"items": function($node) {
var tree = $("#plBox2").jstree(true);
return {
"Info": {
"separator_before": false,
"separator_after": false,
"label": "Info",
"action": function (obj) { document.getElementById('finInfo').style.display='block';
}
},
"Create": {
"separator_before": false,
"separator_after": false,
"label": "Create",
"action": function (data) {
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference);
inst.create_node(obj, {}, "last", function (new_node) {
new_node.data = {file: true};
setTimeout(function () { inst.edit(new_node); },0);
});
}
},
"Rename": {
"separator_before": false,
"separator_after": false,
"label": "Rename",
"action": function (obj) {
tree.edit($node);
rename();
}
},
"Remove": {
"separator_before": false,
"separator_after": false,
"label": "Remove",
"action": function (obj) {
tree.delete_node($node);
}
}
};
}
},
HTML:
<div class="2colWrap">
<div class="col1">
<div id="plBox2"></div>
</div>
<div class="col2">
<div id="finishBox"></div>
</div>
</div>
Thanks!

You can use this statement below!
"Rename": {
"separator_before": false,
"separator_after": false,
"label": "Rename",
"action": function (obj) {
console.log("waht?");
currentNode = $node;
//tree.edit($node);
tree.edit('j1_1', null, function (node, status) {
debugger;
console.log("old name: " + node.original.text);
console.log("new: " + node.text);
console.log(arguments);
});
}
},

Related

How can i get all GUID's in parents and children where enabled = true

I have a need to get a list of all nodes (guid) in my json doc where the enabled key is set to true. What is the best and most effective way to read all parent nodes as well as possible children. In my case children will always be under the items key and children can also have there own children. I came up with some basic script that will check 2 levels deep but i was hoping there is a better approach which will make this more flrxible where i dont have to hardcode each level.
const enabledguid = []
function getenabled() {
mydata.jsondoc.forEach(i => {
if (i.enabled === true) {
enabledguid.push(i.guid)
}
// Check if Parent has children
if (i.items && i.items.length > 0){
console.log('we have children ' + i.items.length)
i.items.forEach(i => {
if (i.enabled === true) {
enabledguid.push(i.guid)
}
if (i.items && i.items.length > 0){
console.log('Child has children ' + i.items.length)
i.items.forEach(i => {
if (i.enabled === true) {
enabledguid.push(i.guid)
}
})
}
})
}
})
console.log(enabledguid)
}
getenabled()
Here is a sample of a json file
[
{
"enabled": true,
"guid": "F56AAC06-D2EB-4E1C-B84D-25F72973312E",
"name": "Farms",
"items": [
{
"enabled": true,
"guid": "144C0989-9938-4AEC-8487-094C23A5F150",
"name": "New Farm List"
},
{
"enabled": false,
"guid": "8FBA7B0B-566E-47CD-885B-1C08B57F34F6",
"name": "Farm Lists"
},
{
"enabled": true,
"guid": "FCD36DBD-0639-4856-A609-549BB10BEC1A",
"name": "Farm Upload"
},
{
"enabled": false,
"guid": "4264DA98-1295-4A65-97C6-313485744B4D",
"name": "Campaign",
"items": [
{
"enabled": false,
"guid": "9CBDC6BB-5B3D-4F53-B846-AFE55F34C1E9",
"name": "New Campaign"
},
{
"enabled": true,
"guid": "281490B5-C67D-4238-9D52-DE1DFA373418",
"name": "Campaign List"
}
]
}
]
},
{
"enabled": true,
"guid": "1A9127A3-7AC7-4E07-AFA0-B8F8571B1B14",
"name": "Vendor",
"items": [
{
"enabled": true,
"guid": "6E6B4DA9-D99D-42D8-A4FE-7C7A82B9F1BE",
"name": "Vendor List"
},
{
"enabled": false,
"guid": "63A61762-75FB-466A-8859-25E184C3E016",
"name": "Add Vendor"
}
]
}
]
This is a great exercise to learn about recursive functions, look it up.
In this problem the base case will be when you get to an item that does not have a subset of items.
const enabledguid = []
function getenabled(items) {
items.forEach(item => {
if (item.enabled === true) {
enabledguid.push(item.guid)
}
if (item.items) {
getenabled(item.items)
}
})
}
getenabled(jsondoc)
console.log(jsondoc)
based on what i found on recursive I came up with this one which does also do the same job.
mydata.filter( item => {
iratedObject(item)
})
function iratedObject(obj) {
for (prop in obj){
if(typeof(obj[prop]) =="object"){
iratedObject(obj[prop]);
} else {
if(obj['enabled'] === true && prop === 'guid'){
enabledguid.push(obj['guid'])
}
}}
}

Loop fetches all the words in 1 input field

as you can see in the picture below, my words 'es' and 'presso' are put into one input field instead of 'es' in one and 'presso' in another input field.
how my JSON looks like:
{
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [
{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}
]
},
"dataType": "json"
}
}
This is how my loop looks like:
$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word) // starts with 0
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
});
to zoom in on the loop where I fetch the syllables:
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
the function where I create the syllable inputs:
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control syllable' + SyllablesID++,
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'name': 'Syllablescounter['+ SyllablesID++ +']'
});
return wpInput;
}
what is it that I am doing wrong? (I did declare the variable SyllablesID so don't worry about that part).
var data = {
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [
{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}
]
},
"dataType": "json"
}
};
function draw(data){
for (ex of data.main_object.main_object.exercises){
for( sy of ex.syllables){
$("#container").append(`<input type="text" value="${sy}">`)
}
}
}
draw(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container"><div>
syllables is an array as per to posted JSON so you'll have to get each value and add it as a value to the input element. You can again use .map or for/forEach etc to loop through syllabus array and add the array entries to input values
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$.map(exer.syllables, function(syll, i){
$(".syllable" + i).val(syll);
})
});

Deleting a key in JSON while making ajax call from javascript

I am new to java script and ajax. I have a JSON and I want to remove outputs cell in this JSON:
{
"cells": [{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "print(\"hi\")",
"execution_count": 1,
"outputs": [{
"output_type": "stream",
"text": "hi\n",
"name": "stdout"
}]
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "Python [Root]",
"display_name": "Python [Root]",
"language": "python"
},
"anaconda-cloud": {},
"language_info": {
"pygments_lexer": "ipython3",
"version": "3.5.0",
"codemirror_mode": {
"version": 3,
"name": "ipython"
},
"mimetype": "text/x-python",
"file_extension": ".py",
"name": "python",
"nbconvert_exporter": "python"
},
"gist": {
"id": "",
"data": {
"description": "Untitled5.ipynb",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
and this is my attempt on removing the outputs cell. This piece of code posts the data to above mentioned JSON:
"use strict";
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
var outputs = data.cells;
var data_dup = _objectWithoutProperties(data, ["outputs"]);
var id_input = $('#gist_id');
var id = params.gist_it_personal_access_token !== '' ? id_input.val() : '';
var method = id ? 'PATCH' : 'POST';
// Create/edit the Gist
$.ajax({
url: 'https://api.github.com/gists' + (id ? '/' + id : ''),
type: method,
dataType: 'json',
data: JSON.stringify(data_dup),
beforeSend: add_auth_token,
success: gist_success,
error: gist_error,
complete: complete_callback
});
};
But this code doesnt work. Can some one please guide how can we directly strip a key(outputs in this case) from ajax call and post it to JSON.
This is a gist extension of jupyter notebook and I am trying to strip output while posting it to gist on github
function _objectWithoutProperties(obj, key="outputs") { obj.cells.forEach(cell=>delete(cell[key])); }
If you use ES6, you can use this syntax to remove outputs:
{
...data,
cells: data.cells.map(({ outputs, ...otherProps }) => otherProps),
}
Note: data is your complete object.

Multiple Datatables on dynamic tabs

i have developed a dynamic tab mechanism for my web application that any internal content will load using ajax in a new tab which will be appended at the last active tab something like tab functionality in browsers for executing loaded content js i simply have a namespace custom html5 data tag witch is the name of the script and i execute the init() method of it when a new tab is created, it works well on simple jquery scripts but when i try to load pages with jQuery Datatable in them which i'm using for reports my report filter form only works on the last datatable, i have no idea how to solve this issue, here is my tabs.js and reports.js code the second one is the Datatable javascripts.
tabs.js:
(function() {
// open e new tab:
var tabs_label = 1;
var tab_id = 1;
var tabs_num = 1;
var defaults_open = false;
var reports_open = false;
var ns ;//needs change
$('.tab-link').live('click',function(e) {
var parent = $(this);
var href = $(this).attr('href');
if (href == '/defaults/' && defaults_open){
e.preventDefault();
bootbox.alert('تب تعریف پیش فرض ها باز می باشد!');
}
// else if(href == '/report/' && reports_open){
// e.preventDefault();
// bootbox.alert('تب گزارش ها باز می باشد');
// }
else{
var tab_name = $(this).attr('data-name');
e.preventDefault();
tab_id ++;
if (tabs_num > 6) {
bootbox.alert('تب های باز شده بیش از حد مجاز است.');
}
else {
$('.tab-pane').filter('.active').removeClass('active');
$.blockUI({ message: $('#wait-icon'), css: {width: '64px', height: '64px' }});
var content = $('<div></div>', {
class:"tab-pane dynamic-tab active",
id:tab_id,
});
content.appendTo('div#main-tabs');
$('ul.nav-tabs li.active').removeClass('active');
var new_li = $("<li class='active' data-type='"+href+"'><a style='float:left' class='tabbtn' href="+tab_id+" data-toggle='tab'>"+tabs_label+" - "+tab_name+"</a><a style='float:right' class='close' id='tabClose'><i class='icon-remove'></i></a></li>")
new_li.appendTo('ul#tabs');
content.load( href + ' div#arya', function(response, status, xhr) {
if(parent.attr('namespace')){
ns = eval(parent.attr('namespace'));
if(ns.root){
ns.root = content;
}
ns.init();
}
$.unblockUI();
if(status == 'error'){
bootbox.alert("در حال حاضر سرور با مشکل مواجه است", "خروج", function(){
new_li.find("a.close").trigger('click');
});
}
});
tabs_num++;
tabs_label++;
if(href == '/defaults/'){
defaults_open = true;
}
else if(href == '/report/'){
reports_open = true;
}
}
}
});// sell tab name needs work.
// tab activatior function
$('#tabs a.tabbtn').live('click', function(e) {
e.preventDefault();
var id = $(this).attr('href');
var selector = 'div#' + id;
$('.dynamic-tab').filter('.active').removeClass('active');
var new_tab = $('.dynamic-tab').filter(selector);
new_tab.addClass('active');
console.log(new_tab);
ns.root = new_tab;
});
// close a tab:
$('a#tabClose').live('click', function(e) {
e.preventDefault();
$this = $(this);
var a = $this.siblings('a');
var li = $this.parent();
console.log(li);
if(li.attr('data-type') == '/defaults/'){
defaults_open = false;
}
else if(li.attr('data-type') == '/report/'){
reports_open = false;
}
var id = a.attr('href');
var div = $('div#' + id);
if (div.hasClass('active')){
var last = div.siblings('div.tab-pane').last();
last.addClass('active');
ns.root = last;
}
div.detach();
var li = a.parent();
if (li.siblings('.active').length == 0){
li.siblings('li').last().addClass('active');
}
li.detach();
tabs_num--;
tabs_label--;
});
})();
reports.js:
var reports = {
'root': $('.tab-pane#defaults_init'),
'table_init': function() {
var oTable;
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource ) {
if ( typeof sNewSource != 'undefined' )
oSettings.sAjaxSource = sNewSource;
console.log($(this));
this.fnClearTable( this );
this.oApi._fnProcessingDisplay( oSettings, true );
var that = this;
var myData = new Array({ "name": "name", "value": reports.root.find('#name').val()}, { "name": "family", "value": reports.root.find('#family').val()}, { "name": "national_id", "value": reports.root.find('#national_id').val()}, { "name": "city", "value": reports.root.find('#city').val()}, { "name": "job", "value": reports.root.find('#job').val()}, { "name": "date_from", "value": reports.root.find('#date_from').val()}, { "name": "date_to", "value": reports.root.find('#date_to').val()}, { "name": "age_from", "value": reports.root.find('#age_from').val()}, { "name": "age_to", "value": reports.root.find('#age_to').val()}, { "name": "credit_from", "value": reports.root.find('#credit_from').val()}, { "name": "credit_to", "value": reports.root.find('#credit_to').val()});
$.ajax({
url: oSettings.sAjaxSource,
dataType: 'json',
data: myData,
type: "POST",
success: function(json) {
/* Got the data - add it to the table */
for ( var i=0 ; i<json.aaData.length ; i++ ) {
that.oApi._fnAddData( oSettings, json.aaData[i] );
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw( that );
that.oApi._fnProcessingDisplay( oSettings, false );
}
});
}
},
'init': function(){
oTable = reports.root.find('.targetTable').dataTable( {
"sDom": "<'row-fluid'r<'span12'l>>t<'row-fluid'<'span6'p><'span6'i>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sUrl": "/media/translation/dataTables.persian.txt"
},
"sAjaxSource": "/report/ajax/customers/",
"sServerMethod": "POST",
"bDestroy": true,
// "bRetrieve": true,
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "name", "value": reports.root.find('#name').val()} );
aoData.push( { "name": "family", "value": reports.root.find('#family').val()});
aoData.push( { "name": "national_id", "value": reports.root.find('#national_id').val()} );
aoData.push( { "name": "city", "value": reports.root.find('#city').val()} );
aoData.push( { "name": "job", "value": reports.root.find('#job').val()} );
aoData.push( { "name": "date_from", "value": reports.root.find('#date_from').val()} );
aoData.push( { "name": "date_to", "value": reports.root.find('#date_to').val()} );
aoData.push( { "name": "age_from", "value": reports.root.find('#age_from').val()} );
aoData.push( { "name": "age_to", "value": reports.root.find('#age_to').val()} );
aoData.push( { "name": "credit_from", "value": reports.root.find('#credit_from').val()} );
aoData.push( { "name": "credit_to", "value": reports.root.find('#credit_to').val()} );
console.log(aoData);
},
"aoColumns": [
{ "mDataProp": "name" },
{ "mDataProp": "family" },
{ "mDataProp": "national_id" },
{ "mDataProp": "birthday" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "phone" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "cellphone" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "email" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "city" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "country" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "address" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "job" },
{ "mDataProp": "credit" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "age" ,"bSearchable": false, "bVisible": false},
{ "mDataProp": "creation_time" ,"bSearchable": false, "bVisible": false},
],
} );
/* Add a click handler to the rows - this could be used as a callback */
$('#targetTable tbody tr').live('click', function () {
var aData = oTable.fnGetData( this );
infoTpl = "<div class='row-fluid span12'><table class='table table-striped'><tbody>";
infoTpl += "<tr><td>نام: <span>"+aData['name']+"</span></td><td>نام خانوادگی: <span>"+aData['family']+"</span></td><td>کد ملی: <span>"+aData['national_id']+"</span></td><td>تاریخ تولد: <span>"+aData['birthday']+"</span></td></tr>";
infoTpl += "<tr><td>تلفن: <span>"+aData['phone']+"</span></td><td>تلفن همراه: <span>"+aData['cellphone']+"</span></td><td colspan='2'>ایمیل: <span>"+aData['email']+"</span></td></tr>";
infoTpl += "<tr><td colspan='2'>آدرس: <span>"+aData['address']+"</span></td><td>شهر: <span>"+aData['city']+"</span></td><td>کشور: <span>"+aData['country']+"</span></td></tr>";
infoTpl += "<tr><td>سن: <span>"+aData['age']+"</span></td><td>میزان اعتبار: <span>"+aData['credit']+"</span></td><td>تاریخ ایجاد در سیستم: <span>"+aData['creation_time']+"</span></td></tr>";
infoTpl += "</tbody></table></div>";
reports.root.find('#targetInfo').html(infoTpl);
reports.root.find('#targetInfo > div > table > tbody > tr > td > span').css("color","navy");
$(this).toggleClass('row_selected');
} );
reports.root.find('#queryForm').submit(function() { // catch the form's submit event
oTable.fnReloadAjax();
return false;
});
},
};
$(document).ready(function () {
reports.table_init();
});

jstree, disable file nodes

how can i disable file nodes so that the tree only displays folders and not files, this is my code currently,
$(document).ready(function () {
//$("#MySplitter").splitter();
setupSplitter();
$("#divJsTreeDemo").bind("select_node.jstree", function (e, data) {
// if (document.location.href != data.rslt.obj.children("a").attr("href")) {
// document.location.href = data.rslt.obj.children("a").attr("href");
//
var id = data.rslt.obj.attr("id").replace("node", "");
// var tree = jQuery.jstree._reference("#divJsTreeDemo");
// var currentNode = tree._get_node(null, false);
// tree.refresh(currentNode);
GetChildObjects(id);
}).delegate("a", "click", function (e) {
//$("#divJsTreeDemo").jstree("toggle_node", this);
}).jstree({
"themes": {
"theme": "default",
"dots": false,
"icons": false
},
"plugins": [
"core", "themes", "json_data", "types", "ui"
],
"types": {
// I set both options to -2, as I do not need depth and children count checking
// Those two checks may slow jstree a lot, so use only when needed
"max_depth": -2,
"max_children": -2,
// I want only `drive` nodes to be root nodes
// This will prevent moving or creating any other type as a root node
"valid_children": ["drive"],
"types": {
// The default type
"default": {
// I want this type to have no children (so only leaf nodes)
// In my case - those are files
"valid_children": "none",
// If we specify an icon for the default type it WILL OVERRIDE the theme icons
"icon": {
"image": "../../Repository/Images/file.png"
}
},
// The `folder` type
"folder": {
// can have files and other folders inside of it, but NOT `drive` nodes
"valid_children": ["default", "folder"],
"icon": {
"image": "../../Repository/Images/folder.png"
}
}
}
},
"json_data": {
"ajax": {
"type": "POST",
"url": "GetTreeNodes",
"data": function (n) {
return { id: n.attr ? n.attr("id").replace("node", "") : 0 };
},
"async": true,
"success": function (data) {
RenderFileFolder(data);
}
}
}
});
});

Categories

Resources