set drag and drop child node to display json array in table - javascript

So question says by themselves. I did an example here
or or look on this code:
html
<div id="jstree">
<ul>
<li>Root
<ul>
<li>Parent1
<ul>
<li>Child1</li>
<li>Child2</li>
</ul>
</li>
<li>Parent2
<ul>
<li>Child1</li>
<li>Child2</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="form-group">
<input id="left" type="file" class="file" data-upload-url="/upload">
</div>
js
var array = [
{
"name": "Parent1",
"id": "1",
"description": "An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3) "
},
{
"name": "Parent2",
"id": "2",
"description": "A jQuery plugin to select multiple elements with checkboxes :)"
},
{
"name": "Parent1",
"id": "3",
"description": "Show/hide password plugin for twitter bootstrap."
}
];
var array2 = [
{
"subname": "Parent101",
"subid": "101",
"description": "An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3) "
},
{
"subname": "Parent202",
"subid": "202",
"description": "A jQuery plugin to select multiple elements with checkboxes :)"
},
{
"subname": "Parent101",
"subid": "303",
"description": "Show/hide password plugin for twitter bootstrap."
}
];
var $table = $('#table');
var $study = $('#jstree');
$(function () {
$table.bootstrapTable({
formatNoMatches: function () {
return "This table is empty...";
}
});
$('#jstree')
.on('select_node.jstree', function(event, data){
// ===== Initialize parent =====
var loMainSelected = data;
uiGetParents(loMainSelected);
function uiGetParents(node) {
try {
var level = node.node.parents.length;
var elem = $('#' + node.node.id);
var parent = node.node.text;
for (var ln = 0; ln <= level - 1; ln++) {
elem = elem.parent();
var child = elem.children()[-1];
if (child != undefined) {
parent = child.text;
}
}
console.log(parent);
}
catch (err) {
console.log('Error in uiGetParents');
}
}
// ===== Click event on node =====
for(var i = 0; i < data.selected.length; i++) {
var node = data.instance.get_node(data.selected[i]).text;
if (node == "Child1") {
$(function () {
$table.bootstrapTable('refreshOptions',
{
data: array,
columns: [
{
title:"Name",
field:"name"
},
{
title:"Id",
field:"id"
},
{
title:"Description",
field:"description"
}
]
});
});
}
else if (node == "Child2"){
$(function () {
$table.bootstrapTable('refreshOptions',
{
data: array2,
columns: [
{
title:"Subname",
field:"subname"
},
{
title:"Subid",
field:"subid"
},
{
title:"Description",
field:"description"
}
]
});
});
}
}
})
.jstree({
"core" : {
"themes": {
"url": true,
"icons": true,
"dots": true
}
}
});
});
I want to create drag and drop node, so user could drag it and drop it into to the droppable window and he'll see the table with data. Separately everything works fine. Jstree is loading, eventHandler on click works well and you can see table by clicking and even drag and drop window works fine and display every file which user will drop into it but how to connect all of this stuff, has anyone idea?

For that you will have to use the dnd plugin and listen to drag-drop event as below. Check demo - Fiddle.
$(document).on('dnd_stop.vakata', function(e, data) {
for (var i = 0; i < data.data.nodes.length; i++) {
var node = $('#jstree').jstree().get_node(data.data.nodes[i]).text;
if (node == "Child1") {
$table.bootstrapTable('refreshOptions', {
data: array,
columns: [{
title: "Name",
field: "name"
}, {
title: "Id",
field: "id"
}, {
title: "Description",
field: "description"
}]
});
} else if (node == "Child2") {
$table.bootstrapTable('refreshOptions', {
data: array2,
columns: [{
title: "Subname",
field: "subname"
}, {
title: "Subid",
field: "subid"
}, {
title: "Description",
field: "description"
}]
});
}
}
});

Related

How click to open popup Organisational Chart Plugin With jQuery

this is tree view on my website based on jquery org chart plugin, this tree created dynamically and also create children.
code is :
$(function() {
var datascource = {
'name': 'Kirby Cochran',
'title': '5061',
'children': [
{
"name": "Sharon Edwards",
"title": "11454",
"children": [
{
"name": "Kirby Cochran",
"title": "5061-kr",
"children": [
{
"name": "Michael Wach",
"title": "5063"
}
]
},
{
"name": "Phil Ungricht",
"title": "6189",
"children": [
{
"name": "Elaine 2 Cochran",
"title": "10238"
}
]
},
{
"name": "Roberto Montero",
"title": "5371"
}
]}]};
var oc = $('#chart-container').orgchart({
'data' : datascource,
'nodeContent': 'title',
'draggable': true,
'dropCriteria': function($draggedNode, $dragZone, $dropZone) {
if($draggedNode.find('.content').text().indexOf('manager') > -1 && $dropZone.find('.content').text().indexOf('engineer') > -1) {
return false;
}
return true;
}
});
oc.$chart.on('nodedropped.orgchart', function(event) {
console.log('draggedNode:' + event.draggedNode.children('.title').text()
+ ', dragZone:' + event.dragZone.children('.title').text()
+ ', dropZone:' + event.dropZone.children('.title').text()
);
});});
here requirement is if clicked any boxes open the popup and show details of customers. org chart
Here is some code snippet to load a pop-up
$(.node).click(function(){
var id = $(this).attr('id');
// use ajax here and getdata using id then display a modal and populate it
});

Creating dynamic select forms based on selection

I am working on a small project.
The initial select form has N options.
Making a selection will pop up another select form based on what it is.
Example: Choose a pet: dog, cat (Chooses dog), displays types of dogs.
I am doing this using JSON and JS but im not sure I have the correct understanding of how things should be working.
What my thought process is for this, when a selection is made.. send that string to a method and then search the JSON object for that string, pull that data and create the new select.
However, it doesnt appear to be working and I think my lack of knowledge with both is hindering my progress here.
JSON
var obj = {
"option":[
{
"text":"Choose Team",
"value":"choose"
},
{
"text":"Eagles",
"value":"d"
},
{
"text":"Falcons",
"value":"c"
},
{
"text":"Browns",
"value":"b"
}
],
"Eagles":[
{
"text":"Choose Player",
"value":"Choose"
},
{
"text":"Eagles",
"value":"d"
},
{
"text":"Falcons",
"value":"c"
},
{
"text":"Browns",
"value":"b"
}
]
};
And then the JS function that creates a new select box based on the selection string
function changeSelect(select){
var test = select.options[select.selectedIndex].text;
for(var i = 0; i < obj.test.length; i++){
var objOption = document.createElement( 'option' );
objOption.setAttribute( 'value', obj.test[i].value);
objOption.appendChild( document.createTextNode( obj.test[i].text) );
}
}
Is there a reason obj.Eagles[i].text will create my new select form with the correct values but obj.test[i].text doesn't work? (Text is a variable with the String "Eagles" assigned to it)
try this... I had to change the data slightly.
(function(select1, select2) {
select1 = document.getElementById(select1);
select2 = document.getElementById(select2);
var obj = {
"option": [{
"text": "Choose Team",
"value": "choose"
}, {
"text": "Eagles",
"value": "Eagles"
}, {
"text": "Falcons",
"value": "Falcons"
}, {
"text": "Browns",
"value": "Browns"
}],
"Eagles": [{
"text": "Choose Player",
"value": "Choose"
}, {
"text": "Agholor, Nelson",
"value": "d"
}, {
"text": "Ajirotutu, Seyi",
"value": "c"
}, {
"text": "Bradford, Sam",
"value": "b"
}]
};
function populateSelect(select, data) {
for (var i = 0, objOption, element; element = data[i++];) {
objOption = document.createElement('option');
objOption.value = element.value;
objOption.innerHTML = element.text;
select.appendChild(objOption);
}
}
function changeSelect2(event) {
var test = event.target.value,
innerArray = obj[test];
select2.options.length = 0;
if (innerArray) {
populateSelect(select2, innerArray);
}
}
populateSelect(select1, obj.option);
select1.addEventListener("change", changeSelect2, false);
})("select1", "select2");
<select id="select1"></select>
<select id="select2"></select>

JQuery parseJSON and populate a second selection box

What i would like to happen is when i select an item from the first selection box, the 2nd selection box populates from a parseJSON.
I have 2 selection boxes: #web and #cats
web: has (at the moment) 3 options - All Websites (value=0), Website 1 (value=1) and Website 2 (value=2)
When i select from #web i should only get the categories for that particular website, however in PHP i have already considered "All Websites" and it duplicates the categories into each web object, but i also added "All Websites" to the json array, so that if it is reselected the selection box will repopulate.
This is the PHP Function (To create the JSON):
function catWebMix($user) {
$categories = getCategories($user);
$webAll = array('ID'=>0, 'WebID'=>'All', 'WebName'=>'All Websites');
$webSites = getWebsites($user);
array_unshift($webSites,$webAll);
$output = array();
foreach ($webSites as $k => $v) {
$output[$k] = $v;
foreach ($categories as $key => $value) {
if ($value['WebID'] == '0') {
$value['WebID'] = $v['ID'];
$output[$k]['Category'][] = $value;
} else if ($value['WebID'] == $v['ID']) {
$output[$k]['Category'][] = $value;
}
}
}
return array($output, json_encode($output));
exit;
}
I assign a variable to Smarty.
$webCats = catWebMix($user);
$smarty->assign('webCats', $webCats);
I then call it in JQuery. This is my failed attempt at creating the selection boxes change, im unsure on how to do it.
<script type="text/javascript">
var obj = $.parseJSON({$webCats[1]});
$('#web').on('change', function () {
var web = $(this).val();
$.each(obj, function () {
if (web == obj.ID) {
$.each(obj.Category, function (i,v) {
$('#cats').append("<option>"+v[3]+"</option>");
});
}
});
});
</script>
What i want it to do:
Remove all option attributes in #cats
Repopulate #cats with the data from the parseJson, based on the value from #web. #web value = (first) ID in JSON.
Place Category.ID as value for option, and Category.CatTitle as text
The json array looks like the following:
[
{
"ID": 0,
"WebID": "All",
"WebName": "All Websites",
"Category": [
{
"ID": "1",
"WebID": 0,
"CatTitle": "Category 1"
}
]
},
{
"ID": "1",
"WebID": "web1",
"WebName": "Website 1",
"Category": [
{
"ID": "1",
"WebID": "1",
"CatTitle": "Category 1"
},
{
"ID": "2",
"WebID": "1",
"CatTitle": "Category 2"
}
]
},
{
"ID": "2",
"WebID": "web2",
"WebName": "Website 2",
"Category": [
{
"ID": "1",
"WebID": "2",
"CatTitle": "Category 1"
}
]
}
]
Thanks for any help!
I did it! This was the code i used in case others have issues.
<script type="text/javascript">
var webCats = {$webCats[1]};
$('#web').on('change', function () {
var web = $(this).val();
$.each(webCats, function (k, o) {
if (web == o.ID) {
$('#cats option').remove();
$.each(o.Category, function (i, v) {
$('#cats').append("<option value=\""+v.ID+"\">"+v.CatTitle+"</option>");
});
}
});
});
</script>

PhoneJs: update dynamically slideout

I would like to update a specific field in slideout from database(websql), to show the current user and he can access to his profil.
The targert is : title: log1, for that I used save:function (), and I have one record in database.
I spent many days searching but until now no solution.
Someone can help please.
Index
//...
<script type="text/javascript">
$(function() {
slideOut.app.navigate();
});
slideOut.Home = function (params) {
return {};
};
</script>
</head>
<body>
<div data-options="dxView : { name: 'Home', title: 'Slide Out' } " >
<div data-options="dxContent : { targetPlaceholder: 'content' } " >
</div>
</div>
</body>
</html>
App.config:
window.slideOut = $.extend(true, window.slideOut, {
var log1;
save:function (){
var db = openDatabase("dossierpatient", "1.0", "BD patient", 32678);
db.transaction(function(transaction){
transaction.executeSql("SELECT * FROM patient;", [], function(transaction,result){
for (var i=0; i< result.rows.length; i++) {
log1 = result.rows.item(i).login;
console.log(log1 + "\n ");
}
});
});
return log1;
}
"config": {
"navigationType": "slideout",
"navigation": [
{
"title": log1,
"action": "#",
"icon": "todo"
},
{
"title": "Item 2",
"action": "#",
"icon": "tips"
},
{
"title": "Item 3",
"action": "#",
"icon": "card"
},
{
"title": "Item 4",
"action": "#",
"icon": "map"
}
]
}
});
app.js
window.slideOut = window.slideOut || {};
$(function() {
// Uncomment the line below to disable platform-specific look and feel and to use the Generic theme for all devices
// DevExpress.devices.current({ platform: "generic" });
slideOut.app = new DevExpress.framework.html.HtmlApplication({
namespace: slideOut,
commandMapping: slideOut.config.commandMapping,
navigationType: "slideout",
navigation: getNavigationItems()
});
slideOut.app.router.register(":view", { view: "Home"});
function getNavigationItems() {
return slideOut.config.navigation; // cherche le contenu du slideOut
}
});
Seems like you have a mistake in app.config.js. The declaration of var log1 should be above extending code. The $.extend should have parameters as valid js objects:
var log1;
$.extend(true, window.slideOut, {
save: ...,
...
}
Move over I wouldn't advice you to add such a code in app config file.
To customize the view title (or whatever you have in your view) use viewModel with observables. For example:
slideOut.Home = function (params) {
var title = ko.observable("title");
var viewModel = {
title: title,
viewShowing: function() {
// TODO: put code fetching title from db and set it on done to observable
title("value");
}
};
return viewModel;
};
The code above will set the title of the view.

Dependent Kendo Grid with Dynamic Filter Preventing Adding Records

Okay, so I have two observable datasources. One uses a model called TestRequest, of which I can have multiples. The other uses a model of TestResult of which multiples can exist for each TestRequest. I have a requestId data item that I am filtering on to populate my dependent grid. With declarative data and a declarative filter everything works fine. If I dynamically set the filter, I can no longer add new records to the filtered datasource. How can I get around this? I was going to set the "foreign" id in a handler on the data source's change event (this is how I maintain client side primary keys just fine). And I can I can tell from my handler that the "add" action is firing, but the editor popup (I am using popup editing on both grids) is not showing? Is there some other magic I need to enable?
Let me know if I need to post code and I will put my html and js up on a server for y'all to look at and criticize :)
Thanks in advance.
Relevant JavaScript:
var TestRequest = kendo.data.Model.define({
id: "Id",
fields: {
"accessionNumber": { type: "string" },
"specimenCollectionDate": { type: "date" },
"specimenReceivedDate": { type: "date" },
"resultReportDate": { type: "date" },
"testDescription": { type: "string" },
"relevantClincalInfo": { type: "string" },
"specimenSource": { type: "string" },
"resultStatus": { type: "string" },
"reasonForTest": { type: "string" },
"comments": { type: "string" }
}
});
var testRequestDataSource = new kendo.data.DataSource({
schema: {
model: TestRequest
}
});
testRequestDataSource.bind("change", function(e) {
if (e.action === "add") {
e.items[0].dirty = true;
kendo.data.ObservableObject.fn.set.call(e.items[0], "Id", viewModel.testsResults.nextRequestId);
viewModel.testsResults.nextRequestId++;
}
});
var TestResult = kendo.data.Model.define({
id: "Id",
fields: {
"requestId": {
type: "number",
editable: false
},
"foo": {
type: "string"
}
}
});
var testResultDataSource = new kendo.data.DataSource({
data: [
{
Id: 1,
requestId: 1,
foo: "bar"
},
{
Id: 2,
requestId: 1,
foo: "baz"
},
{
Id: 3,
requestId: 2,
foo: "beep"
}
],
schema: {
model: TestResult
},
filter: {
"field": "requestId",
"operator": "eq",
"value": 0
}
});
testResultDataSource.bind("change", function(e){
if (e.action === "add") {
e.items[0].dirty = true;
kendo.data.ObservableObject.fn.set.call(e.items[0], "Id", viewModel.testsResults.nextResulttId);
viewModel.testsResults.nextResultId++;
}
});
var viewModel = kendo.observable({
...
testsResults: {
nextRequestId: 1,
nextResultId: 4,
testRequests: testRequestDataSource,
testResults: testResultDataSource,
testRequestChange: function() {
var selectedItems =testRequestGrid.select();
var selectedRow = $(selectedItems[0]);
var selectedUid = selectedRow.data("uid");
var selectedData = testRequestGrid.dataSource.getByUid(selectedUid);
var requestId = selectedData.id;
this.testsResults.testResults.filter({
"field":"requestId",
"operator":"eq",
"value": requestId
});
},
testRequestEdited: function(e) {
var uid = e.model.uid;
// TODO: fix below code to use callback or better event
setTimeout(function() {
testRequestGrid.select(testRequestGrid.tbody.find(">tr[data-uid='"+uid+"']"));
}, 100);
},
....
....
The HTML:
<div id="testsResults">
<h2>Tests/Results</h2>
<fieldset>
<legend>Test Requests</legend>
<div id="testRequests">
<div data-role="grid"
data-bind="source: testsResults.testRequests, events: { change: testsResults.testRequestChange, save: testsResults.testRequestEdited }"
data-editable="popup"
data-selectable="true"
data-toolbar='["create"]'
data-columns='[{"field":"accessionNumber","title":"Accession #"},
{"field":"specimenCollectionDate", "title":"Specimen Collection Date", "hidden":"true"},
{"field":"specimenReceivedDate", "title":"Specimen Received Date", "hidden":"true"},
{"field":"resultReportDate", "title":"Result Report Date", "hidden":"true"},
{"field":"testDescription","title":"Test Description"},
{"field":"relevantClinicalInfo", "title":"Relevant Clinical Information", "hidden":"true"},
{"field":"specimenSource","title":"Specimen Source", "hidden":"true"},
{"field":"resultStatus","title":"Result Status","hidden":"true"},
{"field":"reasonForTest","title":"Reason For Test", "hidden":"true"},
{"field":"comments","title":"Comments","hidden":"true"},
{"command":["edit","destroy"], "title":" ", "width":"170px"}]'>
</div>
</div>
</fieldset>
<fieldset>
<legend>Test Results</legend>
<div id="testResults">
<div data-role="grid"
data-bind="source: testsResults.testResults"
data-editable="popup"
data-selectable="true"
data-toolbar='["create"]'
data-columns='[{"field":"requestId","title": "Test Request ID", "hidden":"true"},
{"field":"foo", "title":"Foo"},
{"command":["edit","destroy"], "title":" ", "width":"170px"}]'>
</div>
</div>
</fieldset>
</div>
Yay! I get to answer my own question. The problem is that the new record does NOT match the filter, so the edit popup cannot display. I added the missing piece in the change event handler of the data source and everything works nifty:
testResultDataSource.bind("change", function(e){
if (e.action === "add") {
e.items[0].dirty = true;
kendo.data.ObservableObject.fn.set.call(e.items[0], "Id", viewModel.testsResults.nextResulttId);
var filters = this.filter().filters;
var requestId = filters[0].value;
kendo.data.ObservableObject.fn.set.call(e.items[0], "requestId", requestId);
viewModel.testsResults.nextResultId++;
}
});

Categories

Resources