In document ready i append div inside body and i am creating a kendo ui window and then inside that window append second div with creating kendo dynamic chart or kendo grid.
When i create this things i'm loading data from AJAX and shows grid normally, but paging and column resizing is not working
Can you help me on this situation?
Here my code
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
url: '../Home/GetChartsAndInformations',
success: function (data) {
for (i = 1; i <= data.length; i++) {
count = data.length;
$("body").append('<div class="chartWindow" id="chartWindow-' + i + '"><div id="chart-' + i + '"></div></div>');
var myWindow = $('#chartWindow-' + i).kendoWindow().getKendoWindow();
myWindow.setOptions({
width: data[i - 1].Width,
height: data[i - 1].Height,
actions: ["Pin","Maximize", "Close"],
position: {
top: data[i - 1].Ypos,
left: data[i - 1].Xpos
},
title: data[i - 1].ChartDescription
});
$("#chart-" + i).append(FillWindowWithCharts(i))
}
}
});
});
function FillWindowWithCharts(number) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '../Home/QuerySelected',
data: { id: number },
success: function (data) {
if (data.length != 0) {
if (data[0].ChartType == "grid") {
myData = data;
createGrid(data[0].Id);
}
else {
if (data[0].IsGroup) {
myData = {
data: data,
group: {
field: data[0].GroupValue
},
sort: {
field: data[0].SortValue
}
}
ToolTipTemplate = "#= dataItem.Value1 #: #= kendo.format('{0:N}',value) #";
}
else {
myData = data
}
series = [{
field: data[0].SeriesField,
labels: {
visible: true
}
}];
categories = {
field: data[0].CategoryField
}
stackValue = data[0].IsStacked;
chartType = data[0].ChartType;
title = data[0].ChartDescription;
createChart(number);
}
}
else {
$("#chart-" + number).html("No Data in this interval!!");
}
}
});
}
function createGrid(number) {
$("#chart-" + number).kendoGrid({
dataSource: myData,
resizable: true,
pageable: {
refresh:true,
pageSize: 5
},
columns: [
{ field: "Value1", title: myData[0].Series1, hidden: myData[0].Series1 == null ? true : false },
{ field: "Value2", title: myData[0].Series2, hidden: myData[0].Series2 == null ? true : false },
{ field: "Value3", title: myData[0].Series3, hidden: myData[0].Series3 == null ? true : false },
{ field: "Value4", title: myData[0].Series4, hidden: myData[0].Series4 == null ? true : false },
{ field: "Value5", title: myData[0].Series5, hidden: myData[0].Series5 == null ? true : false }
]
});
}
function createChart(number) {
$("#chart-" + number).kendoChart({
theme: "metro",
dataSource:myData,
title: {
text: title
},
legend: {
visible: true,
position: "bottom",
labels: {
template: '#: chartType == "pie" ? dataItem.Value1 : chartType == "donut" ? dataItem.Value1 : text #'
}
},
seriesDefaults: {
type: chartType,
stack: stackValue
},
series: series,
valueAxis: {
labels: {
format: "{0}"
}
},
categoryAxis: categories,
tooltip: {
visible: true,
format: "{0}",
template: ToolTipTemplate
}
});
}
Thank you for your help
After i read some kendo dynamic grid data binding articles . I found way how to bind dynamically to grid some blog example
I give an example below
function createGrid(number,from,to) {
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: false,
pageSize: 10,
transport: { //With the transform i can connect data from ajax
read: {
url: "../Home/QuerySelected",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { id: number, from: from, to: to } // I can pass parameter
},
parameterMap: function (options) {
return JSON.stringify(options);
}
},
schema: { // Please be carefull because if you forget schema grid can give different errors. You need to write schema Data and Total and put right place in datasource
data: "Data",
total: "Total"
}
},
resizable: true,
pageable: {
refresh: true
},
sortable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
contains: "Contains"
}
}
},
columns: [
{ field: "Value1", title: myData.Data[0].Series1, hidden: myData.Data[0].Series1 == null ? true : false },
{ field: "Value2", title: myData.Data[0].Series2, hidden: myData.Data[0].Series2 == null ? true : false },
{ field: "Value3", title: myData.Data[0].Series3, hidden: myData.Data[0].Series3 == null ? true : false },
{ field: "Value4", title: myData.Data[0].Series4, hidden: myData.Data[0].Series4 == null ? true : false },
{ field: "Value5", title: myData.Data[0].Series5, hidden: myData.Data[0].Series5 == null ? true : false }
]
});
$(':contains("No Data in this interval!!")').each(function () {
$("#chart-" + number).html($("#chart-" + number).html().split("No Data in this interval!!").join(""));
});
Thanks!
Related
I'm using a Kendo Chart, the first call works fine but when I call
setInterval(getCharts, 800); the charts brings back the old results every time. If I refresh the page the chart brings the updates results. What am i doing wrong?
If I call $(#chartid).data('KendoChart').datasource.read(); it brings error datasource is undefined
function myCallback(result) {
// Code that depends on 'result'
totalcountvar = result;
return totalcountvar;
}
function foo(callback, id) {
$.ajax({
type: "POST",
url: "Data/OutageCountHandler.ashx?id=" + id,
data: "{}",
async: false,
contentType: "text/json; charset=utf-8",
dataType: "json",
success: callback
});
}
function createChart2(chartid, c_title, fieldName, q_id) {
if (q_id == 2) { foo(myCallback, 4); c_title = c_title + totalcountvar; }
if (q_id == 3) { foo(myCallback, 2); c_title = c_title + totalcountvar; }
if (q_id == 4) { foo(myCallback, 3); c_title = c_title + totalcountvar; }
var sharableDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "Data/ChartDataHandler.ashx?id=" + q_id,
dataType: "json"
}
}
});
// Bind data to Chart
$("#" + chartid).kendoChart({
theme: "moonlight",
chartArea: {
width: 800,
height: 400,
},
title: {
text: c_title
},
dataSource: sharableDataSource,
series: [{
field: fieldName.replace(/\s+/g, ''),
name: fieldName,
color: "#3074D8",
noteTextField: "Type",
notes: {
icon: {
visible: false
},
line: {
length: 20,
color: "transparent"
},
label: {
field:"Type",
position: "outside"
}
}
}],
seriesDefaults: {
type: "column",
labels: {
visible: true,
background: "transparent"
}
},
categoryAxis: {
field: "Area",
},
tooltip: {
visible: true,
background: "white",
format: "{0}",
template: "#= series.name #: #= value #"
},
legend: {
position: "bottom"
}
});
}
Hi i have a Kendo grid which works fine but I was wondering if its possible to add another exact one with a button click so i could have multiple instances of the same grid?
I am getting all the data from a sql database.
My code for the grid is ->
function DisplaySearch() {
var textS = $('#searchBox').val();
Textvalue = textS;
$.ajax({
type: "post",
data: JSON.stringify({
search_string: Textvalue,
}),
url: "Search.aspx/display_search",
dataType: "json",
contentType: 'application/json',
success: function (object) {
response(object);
},
complete: function (object) {
},
error: function (object) {
}
});
function response(object) {
$("#searchGrid").kendoGrid({
dataSource: {
data: object.d,
schema: {
model: {
archive_header_key: { type: "number" },
group_Name: { type: "string" },
Server: { type: "string" },
archive: { type: "string" },
display_name: { type: "string" },
file_written: { type: "number" },
session_ID: { type: "string" },
},
},
pageSize: 20,
},
reorderable: true,
navigatable: true,
selectable: "multiple",
scrollable: true,
sortable: true,
filterable: false,
columnMenu: true,
pageable: {
input: true,
numeric: true
},
columns: [
{ field: "archive_header_key", title: "Key", width: 50 },
{ field: "Server", title: "Server", width: 75 },
{ field: "group_Name", title: "Group", width: 75 },
{ field: "archive", title: "Archive", width: 50 },
{ field: "display_name", title: "Display name", width: 300 },
{ field: "file_written", title: "Files", width: 50 },
{ field: "session_ID", title: "Session", width: 200 },
]
});
}
};
any help would be appreciated.
Of course you can! You only need to make sure that the id of the grid is unique.
This code will add a div to a given container and create a grid - with any button click a new grid. Hope it works, I haven't tested it.
var gridNr = 1;
$("#btn").click(function(e){
$("#gridContainer").append("<div id='grid_'" + gridNr + " />");
$("#grid_" + gridNr).kendoGrid({ ... your grid code here ... });
gridNr++;
})
I am working on Kendo Grid (sorting enabled). Delete event is working fine but once i delete all rows in kendo grid and again press column header it starts showing all deleted data. Anyone have idea what i am doing wrong
function GetManagePlanData(_data) {
$.each(_data, function (key, value) {
if (value.Bonus == 'False')
$('#chkBonusHeader').attr('checked', false);
else if (value.MeritIncrease == 'False')
$('#chkMeritIncHeader').attr('checked', false);
});
var isAllBonusSelected = true, isAllMeritSelected = true, isAllStockSelected = true;
$("#tblEligibleEmployees").kendoGrid({
dataSource: {
data:_data,
group: [{ field: "ManagerName" }],// Add manager name here
schema: {
model: {
fields: {
ManagerRelationRefID: { type: "string" },
EmployeeRelationRefID: { type: "string" },
ManagerName: { type: "string" },
EmployeeCode: { type: "string" },
FullName1: { type: "string" },
JoiningDate: { type: "string" },
BusinessUnitName: { type: "string" },
FTE: { type: "string" },
Salary: { type: "string" },
HourlyRate:{ type: "string" },
EmpStatus: { type: "string" },
MeritIncrease: { type: "bool" },
Bonus: { type: "bool" },
BonusTarget: { type: "double" },
Stock: { type: "bool" },
BonusBase: { type: "decimal" },
Delete : { type: "string" }
}
}
},
//pageSize: 20
},
scrollable: false,
sortable: true,
filterable: false,
groupable:false,
//pageable: {
// input: false,
// numeric: false
//},
columns: [
{ field: "ManagerName", hidden: true, title: "Manager Name" },//resource required manager name
{ field: "ManagerRelationRefID", hidden: true, template: "<input id=hdnManagerID#=EmployeeRelationRefID# value=#=ManagerRelationRefID# />" },
{ field: "EmployeeRelationRefID", hidden: true, template: "<input id=hdnEmployeeID#=EmployeeRelationRefID# value=#=EmployeeRelationRefID# />" },
{ field: "EmployeeCode", title: key_EmployeeId, width: "90px" },
{ field: "FullName1", title: key_fullname, width: "140px" },
{ field: "JoiningDate", title: key_hiredt, width: "110px" },
{ field: "BusinessUnitName", title: Key_Location, width: "90px" },
{
field: "Salary", title: key_Salary, width: "90px", template: FormatSalary
},
{
field: "HourlyRate", title: 'Hourly Rate', width: "90px", template: FormatHourlySalary
},
{ field: "FTE", title: Key_FTE, width: "80px" },
{ field: "EmpStatus", title: key_status, width: "70px" },
{
field: "MeritIncrease", title: key_MeritIncrease, template: ApplyMeritChecks, width: "100px",
hidden: (isMeritIncrease == 0 ? true : false),
headerTemplate: '<input type="checkbox" id="chkMeritIncHeader" >' + key_MeritIncrease + ' </input>',
sortable:false
},
{
field: "Bonus", title: key_Bonus, template: ApplyBonusChecks, width: "100px",
hidden : (isBonus==0 ? true:false),
headerTemplate: '<input type="checkbox" id="chkBonusHeader">' + key_Bonus + ' </input>',
sortable: false
},
{ field: "BonusTarget", title: key_BonusTarget, template: FormatBonusTarget, width: "70px", hidden : (isBonus==0 ? true:false) },
{
field: "Stock", title: key_Stock, template: ApplyStockChecks, width: "60px",
hidden: (isStock == 0 ? true : false),
headerTemplate: '<input type="checkbox" id="chkStockHeader" /><label>' + key_Stock + '</label>'
},
{
field:"BonusBase",title:"Bonus Base" ,width:"80px",
template:ApplyBonusBase,
sortable:false
},
{
field:"Delete",title:"",width :"80px",template:ApplyDelete,sortable:false
}
]
}).data("kendoGrid");
$('.k-grid-header .k-header').css('font-weight', 'bold');
$('.k-header[data-field="Delete"]').css('text-indent', '-9999px');
}
function deleteRow(ID) {
jConfirm2(key_Yes, key_No, key_PlanDeleteMsg, "", function (r) {
if (r == true) {
var nxtRow = $('#btndelete-' + ID).parent().parent().next('tr').hasClass("k-grouping-row");
var prvRow = $('#btndelete-' + ID).parent().parent().prev('tr').hasClass("k-grouping-row");
var nxtRowlength = $('#btndelete-' + ID).parent().parent().next('tr').length
// if ((nxtRow || nxtRowlength == 0) && prvRow) {
//var rowToDelete = $('#btndelete-' + ID).parent().parent().prev('tr');
var nextRow = $('#btndelete-' + ID).parent().parent().closest('tr');
var grid = $("#tblEligibleEmployees").data("kendoGrid");
// grid.removeRow(rowToDelete);
grid.removeRow(nextRow);
}
});
}
Do let me know what i am doing wrong my?
Please try refreshing the kendo grid after deleting the record. Following is the code.
$('#GridName').data('kendoGrid').refresh();
We are removing data from Kendo datasource not from database. Our working Code is
if ($('#tblEligibleEmployees').data('kendoGrid').dataSource._data.length == 0) {
$('#tblEligibleEmployees').data().kendoGrid.destroy();
return false;
}
On getting length 0 from kendo datasource destroying kendo grid.
I am using kendo grid and its working fine . I need to check each row of my grid that if it contains a specific value then bind data using one template otherwise the template will be different . Is this possible ? Here is my code
function detailInit(e) {
var isCreateGrid = true;
var masterRowId = e.data.uid;
var data = [];
$.ajax({
type: "GET",
url: 'https://www.domain.com/details?&transactionId=' + e.data.TransactionId,
contentType: "application/json; charset=utf-8",
dataType: 'json',
headers: { 'ccode': compCode },
cache: false,
async: false,
success: function (result) {
var jsonResult = JSON.parse(result);
for (var i = 0; i < jsonResult.length; i++) {
if (jsonResult[i]["OldValue"] == null || jsonResult[i]["OldValue"] == '')
isCreateGrid = true;
else {
isCreateGrid = false;
break;
}
}
if (isCreateGrid) {
for (var i = 0; i < jsonResult.length; i++) {
data.push({ FieldUpdated: jsonResult[i]["ChangeColumns"], Value: jsonResult[i]["NewValue"] });
}
} else {
for (var i = 0; i < jsonResult.length; i++) {
data.push({ FieldUpdated: jsonResult[i]["ChangeColumns"], Was: jsonResult[i]["OldValue"], Now: jsonResult[i]["NewValue"] });
}
}
}
});
var dataSource = new kendo.data.DataSource({ data: data });
if (data.length == 0) {
var grid = $("#logs").data("kendoGrid");
grid.collapseRow("[data-uid='" + masterRowId + "']");
grid.dataSource.read();
} else {
if (isCreateGrid) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: dataSource,
filter: { field: e.data.Log, operator: "contains", value: 'has created' },
columns:
[{ field: "FieldUpdated", title: "Field Updated", width: "50px" },
{ field: "Value", title: "Value", width: "50px" }]
});
} else {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: dataSource,
filter: { field: e.data.Log, operator: "contains", value: 'has created' },
columns:
[{ field: "FieldUpdated", title: "Field Updated", width: "50px" },
{ field: "Was", title: "Was", width: "50px" },
{ field: "Now", title: "Now", width: "50px" }]
});
}
}
}
but this isCreateGrid condition seems to be useless because if he finds any row where isCreateGrid criteria is false then all rows will have template against false criteria .
Yes you can. Kindly refer below code.
$(gridId).kendoGrid({
dataSource: {
data: datasource
},
scrollable: true,
sortable: true,
resizable: true,
columns: [
{ field: "MetricName", title: "Metric", width: "130px" },
{ field: "OnTrack", title: "On Track", template:'#:changeTemplate(OnTrack)#', width: "130px", attributes: { style: "text-align: center !important;" } },
{ field: "CurrentAmount", title: "Current", template: '$ #:parseFloat(CurrentAmount).toFixed(2)#', width: "130px" },
{ field: "RequiredAmount", title: "Required", template: '$ #:parseFloat(RequiredAmount).toFixed(2)#', width: "130px" }
]
});
function changeTemplate(value)
{
Conditions depending on Your Business Logic
if ()
return "HTML Here";
else
return "HTML Here";
}
I've followed this example from the Kendo UI Web Grid code library. I'm looking to modify the existing JavaScript and replace the alert with a method to send the selected item ID to another view with a slightly different grid. Here is the code from the example. Any suggestions?
<div id="grid"></div>
<button id="showSelection">Show selected IDs</button>
<script>
$(document).ready(function () {
//DataSource definition
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
editable: false,
nullable: true
},
ProductName: {
validation: {
required: true
}
},
UnitPrice: {
type: "number",
validation: {
required: true,
min: 1
}
},
Discontinued: {
type: "boolean"
},
UnitsInStock: {
type: "number",
validation: {
min: 0,
required: true
}
}
}
}
}
});
//Grid definition
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
//define dataBound event handler
dataBound: onDataBound,
toolbar: ["create"],
columns: [
//define template column with checkbox and attach click event handler
{ template: "<input type='checkbox' class='checkbox' />" },
"ProductName", {
field: "UnitPrice",
title: "Unit Price",
format: "{0:c}",
width: "100px"
}, {
field: "UnitsInStock",
title: "Units In Stock",
width: "100px"
}, {
field: "Discontinued",
width: "100px"
}, {
command: ["edit", "destroy"],
title: " ",
width: "172px"
}
],
editable: "inline"
}).data("kendoGrid");
//bind click event to the checkbox
grid.table.on("click", ".checkbox" , selectRow);
$("#showSelection").bind("click", function () {
var checked = [];
for(var i in checkedIds){
if(checkedIds[i]){
checked.push(i);
}
}
alert(checked);
});
});
var checkedIds = {};
//on click of the checkbox:
function selectRow() {
var checked = this.checked,
row = $(this).closest("tr"),
grid = $("#grid").data("kendoGrid"),
dataItem = grid.dataItem(row);
checkedIds[dataItem.id] = checked;
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
//on dataBound event restore previous selected rows:
function onDataBound(e) {
var view = this.dataSource.view();
for(var i = 0; i < view.length;i++){
if(checkedIds[view[i].id]){
this.tbody.find("tr[data-uid='" + view[i].uid + "']")
.addClass("k-state-selected")
.find(".checkbox")
.attr("checked","checked");
}
}
}
</script>