Drag JSTree Node into an external div - javascript

I am using Jquery jsTree where i load my data into jstree with json. Below is my code to populate my jsTree
$.ajax({
async: true,
type: "POST",
url: "MasterPageDataService.asmx/GetAllSites",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (jsonData) {
$("#divSitesTree").jstree({
'core': {
'data': jsonData
},
"plugins": ['dnd', "themes", "json_data", "ui"]
});},
});
I get the data populated perfectly.
Now i want to drag a node and drop it onto div element. I have made my div drop able to serve the purpose like this
$(".droppable").droppable({
drop: function (event, ui) {
alert('dropped');
// here i want the id of dropped node
}
});
I don't want to move the node from tree to anywhere , i just want to get the id of the node being dragged and dropped into div. But my problem is that m not even getting the drop event getting fired. e.g i don't get any alert at all.
I have googled the different solutions and tried this so far.
<script>
$(function () {
$('.drag')
.on('mousedown', function (e) {
return $.vakata.dnd.start(e, { 'jstree': true, 'obj': $(this), 'nodes': [{ id: true, text: $(this).text() }] }, '<div id="jstree-dnd" class="jstree-default"><i class="jstree-icon jstree-er"></i>' + $(this).text() + '</div>');
});
$(document)
.on('dnd_move.vakata', function (e, data) {
var t = $(data.event.target);
if (!t.closest('.jstree').length) {
if (t.closest('.drop').length) {
data.helper.find('.jstree-icon').removeClass('jstree-er').addClass('jstree-ok');
}
else {
data.helper.find('.jstree-icon').removeClass('jstree-ok').addClass('jstree-er');
}
}
})
.on('dnd_stop.vakata', function (e, data) {
var t = $(data.event.target);
if (!t.closest('.jstree').length) {
if (t.closest('.drop').length) {
$(data.element).clone().appendTo(t.closest('.drop'));
}
}
});
});
</script>
But what it does, it simply appends the node(icon+text) in my div. But that is not what i want. I just want to get the Id of the node inside an event where i can perform further operation based over the id of the node.
How do I accomplish this task with jsTree? Please Help.

Luckily I have found the solution. Below is the script to get the id of the node being dragged and the id of the target where the node is being dropped
$(document)
.on('dnd_stop.vakata', function (e, data) {
var t = $(data.event.target);
if (!t.closest('.jstree').length) {
if (t.closest('.drop').length) {
alert(data.data.origin.get_node(data.element).id);//node id
alert(data.event.target.id) //target id
}}});});

Related

How to show selected nodes of a tree - JSTree jQuery

I want to show the records in a tree format for which I used JStree plugin of jQuery.
I have successfully implemented the JStree to show records as tree, but I am having issue when a user selects the nodes from the tree for that I also want to show selected nodes as a tree for better representation .. but the code doesn't seems to work perfectly..
Code below renders the tree:
$.ajax({
url: "<?php echo base_url(); ?>Controller_Name/Function_Name",
type: "POST",
data: "code="+code,
success: function(result)
{
$('#jstree').jstree("destroy");
$('#jstree').jstree({
'checkbox': {
three_state: true
},
'plugins': ['search', 'checkbox', 'wholerow'],
'core': {
'data': JSON.parse(result),
'animation': false,
'themes': {
'icons': false,
}
},
'search': {
'show_only_matches': true,
'show_only_matches_children': true
}
});
}
});
I want to show the selected nodes as a tree using the same JStree plugin..
this below code is the one which should give the tree of selected nodes..
$('#jstree').on('changed.jstree', function (e, data){
var objects = data.instance.get_selected(true)
var leaves = $.grep(objects, function (o)
{
return data.instance.is_leaf(e)
})
console.log(leaves);
var json = [];
$.each(leaves, function (i, o){
district_ids();
json.push({"id":o.id, "parent":o.parent, "text":o.text});
});
console.log(json);
$.ajax({
success: function(json){
$('#output').jstree("destroy");
$('#output').jstree({
'plugins': ['wholerow'],
'core': {
'data': json,
//'data': json,
},
});
}
});
});
but the function does not gives the desired result... it keeps loading

AJAX/jQuery generated inputs not recognized by other jQuery scripts

I have what I assume is a relatively simple issue. For testing purposes I have made it so simple so as to locate the issue.
I have a jQuery script that works alongside AJAX to return some results next to checkboxes, here it is below:
$.ajax({
type:'GET',
url: '/customers/details/emails',
dataType:'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i,val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" id="emailCheckboxSelect">'),
$('<td>').text(val)).appendTo('#customerEmails');
});
}
}
});
As you can see near the end, for each result a table row is appended, with a checkbox with an id of "emailCheckboxSelect".
Now to my problem, these are obviously dynamically created elements so I believe this is the issue with this script (a simple dummy just to locate the issue). Here is that script that should work:
$(function(){
$('#emailCheckboxSelect').click(function(){
alert('clicked');
});
});
This doesn't work with the dynamically created elements. However, I did add <input type="checkbox" id="emailCheckboxSelect">Checkbox directly to my page, and this does set off the alert.
So what am I doing wrong and what do I need to do so that jQuery can recognize dynamically created elements?
Try to bind the click event after the $.each(data, function() {}) inside the sucess: function() {}
You are using multiple elements with same id in the DOM : Element IDs should be unique within the entire document.
use classes instead
your code will look like:
$.ajax({
type: 'GET',
url: '/customers/details/emails',
dataType: 'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function() {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {
timeOut: 5000
});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i, val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" class="emailCheckboxSelect" />'),
$('<td>').text(val)).appendTo('#customerEmails');
});
$('.emailCheckboxSelect').click(function(e) {
alert('clicked');
});
}
}
});
Try changing your click event to something like
$('td').on('click', '.emailCheckboxSelect', function () {
alert('clicked');
});
This would work on dynamically created elements. Also, use class instead of id for dynamically created elements.

JStree Async Search

Whe are busy building a web based app. And we inherited the code where the previous developers used jstree so now the whole site consist out of a tree that uses jstree.
Everything worked even the search on the tree, but then we came across a problem where certain tabs loaded too long because of the tree which was too big.
So we went and made the the tree async / lazy loading which works perfectly but know the problem is that the search doesn't work that well.
Because we made a api for the search which works but it doesn't do the call back after new tree has been loaded.
Can someone help because I've been struggling for 3 days now and its giving me a head ache.
// Tree Search
searchAjaxFunction: function () {
var TreeCustomApiRequest = {
nTreeCustomDesc: document.getElementById("tree_search").value,
nUserId: document.getElementById("TrendUserID").value,
nAccessLevel: document.getElementById("hfTrendAccessLevel").value
}
$.ajax({
type: "POST",
data: JSON.stringify(TreeCustomApiRequest),
url: 'api/TreeCustomSearch.aspx',
success: function (jsonData)
{
Tree.dataJson = jsonData;
// Clear the tree.
//Tree.dataJson = jsonData;
if ($("#tree").jstree()) {
$('#tree').jstree(true).settings.core.data = jsonData;
$('#tree').jstree(true).deselect_node(this);
$('#tree').jstree(true).toggle_node(this);
$('#tree').jstree(true).refresh();
}
},
contentType: "application/json"
});
},
onClickFunctionNode: function(node) {
Tree.treeDivIdSelector.jstree(true).toggle_node(node);
},
pluginsArray: ["search", "checkbox", "types", "json_data","html_data"],
treeMenuContextItems: {},
Init: function(initData) {
Tree.dataJson = initData.dataJson;
Tree.treeDivIdSelector = initData.chartDivId;
Tree.searchDivIdSelector = initData.searchDivId;
var apiUriTree = 'api/TreeCustomChildren.aspx';
Tree.treeDivIdSelector.jstree({
"checkbox": {
"keep_selected_style": true,
"three_state": false
},
"plugins": Tree.pluginsArray,
'core': {
'data': function (node, cb) {
// Fetch tree custom parent nodes
if (node.id === "#") {
cb(Tree.dataJson);
}
else {
var _cb = cb;
//Fetch tree custom Child nodes
var TreeCustomApiRequest = {
nUserId: document.getElementById("TrendUserID").value,
nAccessLevel: document.getElementById("hfTrendAccessLevel").value,
nTreeCustomParentId: node.id
}
function recieveData(data) {
cb(data);
}
$.ajax({
type: "POST",
data: JSON.stringify(TreeCustomApiRequest),
url: apiUriTree,
success: recieveData,
contentType: "application/json"
});
}
},
"themes": {
"icons": false
}
},
"contextmenu": {
items: Tree.pluginsArray.indexOf("contextmenu") > -1 ? Tree.treeMenuContextItems : null
}
});
var tree = Tree.treeDivIdSelector.jstree();
function getNode(sNodeID) {
return tree.get_node(sNodeID);
}
Tree.treeDivIdSelector.on('click', '.jstree-anchor', function(e) {
Tree.onClickFunctionNode(this);
}
);
//Tree.searchDivIdSelector.keyup(Tree.searchFunction);
},
The next code is in the client side......
<script type="text/javascript">
$(document).ready(function () {
var dataJson = <%=sTreeViewJson%>
Tree.Init({ dataJson: dataJson, chartDivId: $("#tree") });
$("#btnSearch").click(function () {
// Do the Ajax search
Tree.searchAjaxFunction();
//var value = document.getElementById("tree_search").value;
//Tree.searchFunction();
})
});
</script>
Thank you Nikolay, it was a stupid mistake from me so what I added was just this to my code:
success: function (jsonData, callback )
{
//Goes back to the Callback with the new search data
Tree.Init({ dataJson: jsonData, chartDivId: $("#tree"), searchDivId: $("#tree_search") });
$('#tree').jstree(true).refresh();
}
So I removed the
$('#tree').jstree(true).settings.core.data = jsonData;
$('#tree').jstree(true).deselect_node(this);
$('#tree').jstree(true).toggle_node(this);
Know it gets my data and refreshes the table with the init function while it has my new data.
Hope this also may help someone = ).

How to log "select2" selected value

I use "Select2" as dropdown list.
Now i´d like my page content to change upon my choice in Select2.
I´m stepping forward and have come to this:
JS
$(document).ready(function(){
// display logs
function log(text) {
$('#logs').append(text + '<br>');
}
//SELECT2
$( ".select2_choose_objnr" ).select2({
placeholder: "Välj Objekt..",
ajax: {
url: "php.php",
type: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
}).on("change", function(e) {
log("change val=" + e.val);
});
});
From this Js, i got: val=undefined
How can i change my code to get the selected value/text ?
For v4.0.3
In the change callback, call $(this).val() to retrieve an array of selected values
.on("change", function(e) {
log("change val=" + $(this).val());
});
val() is a function, not a property and you want to call it on $(this)
You can accesss the full data
.on('change', function(e) {
// Access to full data
console.log($(this).select2('data'));
});

tooltips only on first page of table

Hi i have a flexigrid to display some data on my site. Each row has a hyperlink that when the user hovers over it brings up a tool tip containing more information. However this only works for the first page on the table, when i change pages the tool tips stop working. I know this is because i use the tool tips in document.ready but i am unsure on how to solved the problem. any help would be appreciated. I've included a fiddle for the tool tips however the table does not have pagination. See fiddle ive included the code below too. This is called in document.ready
function tooltip(){
$('#tblOrder tr td a').on('mouseenter', function(event) {
var id = $('#tblOrder tr[id*="row"]').attr('id').substr(3);
$(this).qtip({
content: {
text: 'Loading.....',
ajax: {
url: '<%=Url.Action("Alarms") %>',
type: 'POST',
data: {id: id},
success: function (data, status) {
this.set('content.text', data);
},
error: function (xhr) {
console.log(xhr.responseText);
}
}
},
show: {
event: event.type,
ready: true,
effect: function () {
$(this).slideDown();
}
},
hide: {
effect: function () {
$(this).slideUp();
}
}
}, event);
});
};
When you are updating the content inside of #tblOrder you should rebind the event handler or even easier bind the mouseenter event to #tblOrder and filter the event callback with a detailed selector. So instead of your code - use this:
$('#tblOrder').on('mouseenter', 'tr td a', function(event) {

Categories

Resources