Get current data (object/json) from Bootstrap-Treeview - javascript

I am using Bootstrap-Treeview. I need a tree with checkboxes. And i want to send all tree to the server in treview format when button is pressed. But i can't understand how to extract actual data from treeview.
<html xmlns="http://www.w3.org/1999/html">
<head>
<link href="bootstrap-treeview.min.css" rel="stylesheet">
<link href="bootstrap.min.css" rel="stylesheet">
<script src="jquery.js"></script>
<script src="bootstrap-treeview.min.js"></script>
<script>
window.onload = function () {
var object = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1"
},
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
];
$('#tree').treeview({
data: object,
showCheckbox: true,
})
.on('nodeSelected', function (event, data) {
console.log('node selected = ' + JSON.stringify(event) + '; data = ' + JSON.stringify(data));
console.log('object =' + JSON.stringify(object));
console.log('tree =' + JSON.stringify($('#tree').data('treeview')));
console.log('tree 2 =' + JSON.stringify($('#tree')));
console.log('tree 3 =' + JSON.stringify($('#tree').treeview(true)));
});
};
</script>
</head>
<body>
<div id="tree">twetwe</div>
</body>
</html>
After page loads i check any checkbox and than click on any item, so console.log is called. But there is no info about actual state of all treeview. I need that information about all nodes :
{"text":"Child 2","nodeId":3,"parentId":0,"selectable":true,"state":{"checked":false,"disabled":false,"expanded":false,"selected":true}}

Its not possible to get all the nodes of the tree as such because no public method is available on the treeview object that would give the current state of the whole tree .i.e all the nodes.
However it is possible to extract that data indirectly say by combining outputs of treeview.getCollapsed() and treeview.getExpanded() methods into a single object.
<html xmlns="http://www.w3.org/1999/html">
<head>
<link href="bootstrap-treeview.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script src="bootstrap-treeview.min.js"></script>
<script>
window.onload = function () {
var object = [
{text: "Parent 1",
nodes: [{text: "Child 1",
nodes: [{text: "Grandchild 1"}]
},
{text: "Child 2"}
]
},
{text: "Parent 2"} ];
$('#tree').treeview({
data: object,
showCheckbox: true,
}).on('nodeSelected', function (event, data) {
console.log( getAllNodes() );
console.log( JSON.stringify(getAllNodes() ));
console.log('node selected = ' + JSON.stringify(event) + '; data = ' + JSON.stringify(data));
});
};
function getAllNodes(){
var treeViewObject = $('#tree').data('treeview'),
allCollapsedNodes = treeViewObject.getCollapsed(),
allExpandedNodes = treeViewObject.getExpanded(),
allNodes = allCollapsedNodes.concat(allExpandedNodes);
return allNodes;
}
</script>
</head>
<body>
<div id="tree">twetwe</div>`enter code here`
</body>
</html>
However please note that the resultant object is not similar in structure to input object that was supplied to treeview as data. Resultant object may be reformatted to construct an object similar to input object.

Related

Kendo grid highlight all column by external value

I want to highlight the kendo grid cell by matching an external string text.
I googled a lot but found only searching a string in a particular column.
below is the code which works for one column
$("#grid").kendoGrid({
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName" },
{ field: "category" }
],
dataSource: [
{ productName: "Tea", category: "Beverages" },
{ productName: "Coffeete", category: "Beverageste" },
{ productName: "Ham", category: "Foodte" },
{ productName: "Bread", category: "Food" }
]
});
var grid = $("#grid").data('kendoGrid');
var value = 'te';
var regex = new RegExp(value, "gi");
var colIndex = 0;
grid.tbody.find('tr[data-uid]').each(function () {
var td = $(this).find('td:eq(' + colIndex + ')');
var item = grid.dataItem(this);
td.html(item.productName.replace(regex, '<span style="background-color:yellow">' + value + '</span>'));
});
But I want the search the string text across all columns.
Can anyone help me on this?
The best for doing that IMO is to use templates, e.g.:
template: "#= findText(data.fieldName) #"
The template will use a function to create the search highlight which can be something similiar as you already done:
var findText = function findText(text) {
let index = text.indexOf(value),
result = text;
// If substring is found in current text
if (index > -1) {
let regex = new RegExp(value, "gi");
result = result.replace(regex, '<span style="background-color:yellow">' + value + '</span>');
}
return result;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script></head>
<body>
<div id="grid"></div>
<script>
var value = 'co';
var findText = function findText(text) {
let index = text.toLowerCase().indexOf(value),
result = text;
// If substring is found in current text
if (index > -1) {
let regex = new RegExp(`(${value})`, "gi");
result = result.replace(regex, '<span style="background-color:yellow">$1</span>');
}
return result;
};
$("#grid").kendoGrid({
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName", template: "#= findText(data.productName) #" },
{ field: "category", template: "#= findText(data.category) #" }
],
dataSource: [
{ productName: "Tea", category: "Beverages" },
{ productName: "Coffeete", category: "Beverageste" },
{ productName: "Ham", category: "Foodte" },
{ productName: "Bread", category: "Food" }
]
});
</script>
</body>
</html>
Demo in Dojo

SlickGrid and copy text from cell

I'm trying to copy the text contents of a cell - I don't need to be able to paste into Excel or anything, I just want the plaintext content. Highlighting text, right clicking, and selecting copy works as expected (so not the same problem as in SlickGrid and Text Selection since I can select text) but highlighting and pressing ctrl+c does not (nothing gets copied to the clipboard).
I tried commenting out the keypress-handling code in slick.grid.js ($canvas.on("keydown", handleKeyDown) and $focusSink.add($focusSink2).on("keydown"), handleKeyDown)) but no change.
Chrome 61 on Windows 10, if it matters.
Reproduce with the Basic use with configuration example, with enableTextSelectionOnCells set to true:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="shortcut icon" type="image/ico" href="favicon.ico" />
<title>SlickGrid example 1: Basic grid</title>
<link rel="stylesheet" href="../slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="../css/smoothness/jquery-ui-1.11.3.custom.css" type="text/css"/>
<link rel="stylesheet" href="examples.css" type="text/css"/>
</head>
<body>
<div id="myGrid" style="width:600px;height:500px;"></div>
<script src="../lib/jquery-1.11.2.min.js"></script>
<script src="../lib/jquery.event.drag-2.3.0.js"></script>
<script src="../slick.core.js"></script>
<script src="../slick.grid.js"></script>
<script>
var grid;
var columns = [
{id: "title", name: "Title", field: "title"},
{id: "duration", name: "Duration", field: "duration"},
{id: "%", name: "% Complete", field: "percentComplete"},
{id: "start", name: "Start", field: "start"},
{id: "finish", name: "Finish", field: "finish"},
{id: "effort-driven", name: "Effort Driven", field: "effortDriven"}
];
var options = {
enableCellNavigation: true,
enableTextSelectionOnCells: true,
enableColumnReorder: false
};
$(function () {
var data = [];
for (var i = 0; i < 500; i++) {
data[i] = {
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
}
grid = new Slick.Grid("#myGrid", data, columns, options);
})
</script>
</body>
</html>
I was able to get Copy to Clipboard to work using this example:
https://6pac.github.io/SlickGrid/examples/example-excel-compatible-spreadsheet.html
I don't care for paste or much of the other Excel functionality, so I set readOnlyMode on like this:
grid.registerPlugin(new Slick.CellExternalCopyManager({
readOnlyMode : true,
includeHeaderWhenCopying : false,
}));

print object data in table Jquery

Hi i wanna display some values of an object,
the object has the next structure:
{
0:
{ id: "value",
topic: "value",
description: "value",
...
}
1:
{
...
}
}
and this is my code for display in a table with id=cursos
it has an ajax call before so I do this inside .done() method
the thing is that when I use double each to call teh first object and display its attributes it doesn't show anything, but when I call them by its name, without $.each() it is showed in table format,
How can I show the values of my objects in table format using $.each(), just to save code lines note: i have also changed the .html() for .append() and it's the same result.
resultado.done(
function (data){//success
$("#cursos").append($("<tr>").append(
$("<td>").append("Tema"),
$("<td>").append("Indice"),
$("<td>").append("DescripciĆ³n"),
$("<td>").append("Fecha"),
$("<td>").append("Idioma"),
$("<td>").append("Imagen"),
$("<td>").append("Enlaces"),
$("<td>").append("Nivel"),
$("<td>").append("Palabras clave"),
$("<td>").append("Autor"),
$("<td>").append("Escuela"),
$("<td>").append("Categoria"),
$("<td>").append("Subcategoria")
),
$("<tr>").html(
$.each(data, function (key, data1) {
$.each(data1, function (index, datos) {
console.log("index", datos);
$("<td>").append(datos);
})
})
/* if this block comment is removed it works
$("<td>").append(data[0].tema),
$("<td>").append(data[0].indice),
$("<td>").append(data[0].descripcion),
$("<td>").append(data[0].fecha),
$("<td>").append(data[0].idioma),
$("<td>").append(data[0].imagen),
$("<td>").append(data[0].enlaces),
$("<td>").append(data[0].nivel),
$("<td>").append(data[0].keywords),
$("<td>").append(data[0].autorId),
$("<td>").append(data[0].escuelasId),
$("<td>").append(data[0].categoriaId),
$("<td>").append(data[0].subcategoriaId)*/
)
);
//data[0].tema
}//function DONE
);//done
Try something like this:
var dataCollection = {
0: {
id: "id0",
topic: "topic0",
description: "desc0"
},
1: {
id: "id1",
topic: "topic1",
description: "desc1"
},
2: {
id: "id2",
topic: "topic2",
description: "desc2"
}
};
$.each(dataCollection, function(index) {
$("table#cursos").append("<tr>");
$.each(dataCollection[index], function(key, value) {
$("table#cursos").append("<td>" + value + "</td>");
});
$("table#cursos").append("</tr>");
});
See fiddle.
Hope this helps!
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<!--http://stackoverflow.com/a/8563020/3200163-->
<!--http://stackoverflow.com/questions/8562744/how-to-loop-through-this-nested-object-json-array-and-build-an-html-string-with-->
</head>
<body>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script>
var data = {
"sEcho": 1,
"total": "1710",
"aaData": [
[
"Help",
"http:\/\/www.mysite.com\/wp-content\/uploads\/2011\/09\/dt_intfc4e732d1f1276d_4e76fab1e95bd.mp3?King_of_Spain_Entropy_02_Animals_Part_1.mp3",
"1784",
"3",
0,
null,
"0000-00-00 00:00:00"
],
[
"A Day In The Life",
"http:\/\/www.mysite.com\/wp-content\/uploads\/2011\/09\/dt_intfc4e732d1f1276d_4e76f5fc253a1.mp3?JenWood_Zeppelin.mp3",
"3573",
"3",
0,
null,
"0000-00-00 00:00:00"
]
]
}
var str = "";
for (var item in data.aaData) {
str += '<tr>';
for (idata in data.aaData[item]) {
str += '<td>' + data.aaData[item][idata] + '</td>';
}
str += '</tr>';
}
$('body').append("<table>" + str + "</table>");
</script>
</body>
</html>
This code creates a table correctly :)

In a kendo grid, can I set column attributes dynamically with a function?

I've got some code here where I am trying to set a background color of a cell based on the value of the data item: http://dojo.telerik.com/#solidus-flux/eHaMu
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.mobile.all.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1411/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [ {
field: "name",
title: "Name",
attributes: function(e) {
return {
"class": "table-cell",
style: e.name == "Jane Doe" ? "background-color: red" : "background-color: green"
};
}
//attributes: {
//"class": "table-cell",
//style: "text-align: right; font-size: 14px"
//}
} ],
dataSource: [ { name: "Jane Doe" }, { name: "John Doe" }]
});
</script>
</body>
</html>
I realize I could do this with a template, but that would require an extra html element, since you can't change the markup of the td itself. I'd like to use a function to return attributes if that is supported.
You said you don't want to use templates, but I think you were talking about column templates.
You can change the markup of the td itself by using a row template:
<script id="template" type="text/x-kendo-template">
<tr data-uid="#= uid #">
# this.columns.forEach(function(col) {
var val = data[col.field],
css,
style = ''
cClasses = '';
if (typeof col.attributes === 'function') {
css = col.attributes(data);
cClasses = css["class"];
style = css.style
}
#
<td class='#= cClasses #' style='#= style #'>
#= data[col.field] #
</td>
# }) #
</tr>
</script>
For the loop to work, you need to bind your template to the grid though:
var grid = $("#grid").kendoGrid({
columns: [{
field: "name",
title: "Name",
attributes: function (e) {
return {
"class": "table-cell",
style: e.name == "Jane Doe" ?
"background-color: red" : "background-color: green"
};
}
}, {
field: "title",
title: "Title"
}],
dataSource: [{name: "Jane Doe", title: "Dr. Dr."},
{name: "John Doe", title: "Senior Citizen"}]
}).data("kendoGrid");
var template = kendo.template($("#template").html()).bind(grid);
grid.setOptions({
rowTemplate: template
});
(demo)
As an alternative, you could also create attributes like this:
{
field: "name",
title: "Name",
attributes: {
"class": "# if(data.name === 'Jane Doe') { # red # } else { # green # } #"
}
},
This would have the advantage of not using the row template, but you'd have to use the template syntax for the logic.
(demo)
Please try with the below code snippet.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.mobile.all.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1411/js/kendo.all.min.js"></script>
<style>
.greenBG {
background-color:green;
}
.redBG {
background-color:red;
}
</style>
</head>
<body>
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [{
field: "name",
title: "Name",
attributes: function (e) {
return {
"class": "table-cell",
style: e.name == "Jane Doe" ? "background-color: red" : "background-color: green"
};
}
}],
dataSource: [{ name: "Jane Doe" }, { name: "John Doe" }],
dataBound: function () {
dataView = this.dataSource.view();
for (var i = 0; i < dataView.length; i++) {
if (dataView[i].name === "Jane Doe") {
var uid = dataView[i].uid;
$("#grid tbody").find("tr[data-uid=" + uid + "]").addClass("greenBG");
}
else {
var uid = dataView[i].uid;
$("#grid tbody").find("tr[data-uid=" + uid + "]").addClass("redBG");
}
}
}
});
</script>
</body>
</html>
In angular kendo callback e not work
Use this
attributes: {
"ng-confirm-message": "{{this.dataItem.is_active ? \'Are you sure deactive ?\' : \'Are you sure active ?\'}}",
"confirmed-click": "vm.inlineSubmit(this.dataItem.toJSON() ,true)"
}
For Kendo-JQuery.
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [{
field: "name",
headerAttributes: {
"class": "table-header-cell",
style: "text-align: right; font-size: 14px"
}
}]
});
</script>
And this Kendo-MVC
.Columns(columns =>
{
columns.Bound(c => c.ActiveReason).Title("ActiveReason").HeaderHtmlAttributes(new { #class = "table-header-cell" });
})
Some years later but ... the attributes function is not working at all for me, is not even hit, seems pretty but not working (Why is needed a manual class toggle if a functions is provided to do the work? something seems weird).
I make editable cells based on other fields values but also I needed to change the styles
1) Add the validation on field that you want to inject the css class,
//Your other fields configuration
field:"dependentField",
attributes:
{
"class": "# if(data.ImportantField!==true) { # nonEditableCellStyle # } else { # editableCellStyle # }# ",
}
//Your other fields configuration
2) Bind the grid change event and check if some important field has changes, if is the field that controls the style of other cells just call the refresh method
var _kendoGrid = $('#myGrid').data("kendoGrid");
_kendoGrid.dataSource.bind("change", function (e) {
if (e.action === "itemchange") {
if (e.field === "ImportantField") {
_kendoGrid.refresh();
}
}
});
The refresh method will render your grid again, that means your functions weather is a template or an attribute function ( and again, that does not work at all for me) will run and apply the correct sytles, or classes in this case.

jQuery Fancy Tree with Local Array Data

I am trying to implement jQuery FancyTree http://wwwendt.de/tech/fancytree/demo/ with local array data
Referred from https://code.google.com/p/fancytree/
This is the code. But it is not working, No Script Error.But Tree is empty!!!
Even i copied the jQuery, UI versions of the file they using in a demo
site. Still nothing works
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery-ui.custom.js" type="text/javascript"></script>
<link href="ui.fancytree.css" rel="stylesheet" type="text/css" />
<script src="jquery.fancytree.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#tree").fancytree({
onActivate: function (node) {
// A DynaTreeNode object is passed to the activation handler
// Note: we also get this event, if persistence is on, and the
// age is reloaded.
alert("You activated " + node.data.title);
},
children: [ // Pass an array of nodes.
{title: "Item 1" },
{ title: "Folder 2", isFolder: true,
children: [
{ title: "Sub-item 2.1" },
{ title: "Sub-item 2.2" }
]
},
{ title: "Item 3" }
]
});
});
</script>
</head>
<body>
<div id="tree">
</div>
</body>
</html>
I have noticed that source:[] is how you initializes the tree in $("#tabTree").fancytree() initialization call, so your example would be:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery-ui.custom.js" type="text/javascript"></script>
<link href="ui.fancytree.css" rel="stylesheet" type="text/css" />
<script src="jquery.fancytree.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#tree").fancytree({
onActivate: function (node) {
// A DynaTreeNode object is passed to the activation handler
// Note: we also get this event, if persistence is on, and the
// age is reloaded.
alert("You activated " + node.data.title);
},
source: [ // Pass an array of nodes.
{title: "Item 1" },
{ title: "Folder 2", isFolder: true,
children: [
{ title: "Sub-item 2.1" },
{ title: "Sub-item 2.2" }
]
},
{ title: "Item 3" }
]
});
});
</script>
</head>
<body>
<div id="tree">
</div>
</body>
</html>
btw, in case you noticed it, the documentation is quite messy, as they are refactoring the code, the documentation is half what's left from dynatree and the new conventions of fancytree. So expect more weird stuff like that :-)
are the Scriptpath right?
Do you download "jquery.js, jquery-ui.custom.js, ui.fancytree.css and jquery.fancytree.js" ?

Categories