With CanvasJS charts, how can i have 2 charts on one page when using chart functions - canvasjs

Here is my code. Ive researched online and i only can use one window onload thing but i have functions in my charts that i cant remove. Ive tried to put the chart codes into one window onload function but to no avail. Ive also tried putting the chart functions with window.onload into two seperate pages and calling them into one php page, but it doesnt work (im assuming for the same reasons). Thanks :)
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("bar", {
animationEnabled: true,
title:{
text: "Maximum, Minimum and Average Temperatures for the Hot Cars"
},
axisY: {
title: "Temperature (C)",
includeZero: true
},
legend: {
cursor:"pointer",
itemclick : toggleDataSeries
},
toolTip: {
shared: true,
content: toolTipFormatter
},
data: [{
type: "bar",
showInLegend: true,
name: "Maximum",
color: "#fc0303",
dataPoints: [
<?php echo $black_max; ?>,
<?php echo $white_max; ?>,
<?php echo $red_max; ?>,
<?php echo $clear_max; ?>,
<?php echo $silver_max; ?>
]
},
{
type: "bar",
showInLegend: true,
name: "Minimum",
color: "#0314fc",
dataPoints: [
<?php echo $black_min; ?>,
<?php echo $white_min; ?>,
<?php echo $red_min; ?>,
<?php echo $clear_min; ?>,
<?php echo $silver_min; ?>
]
},
{
type: "bar",
showInLegend: true,
name: "Average",
color: "#b503fc",
dataPoints: [
<?php echo $black_avg; ?>,
<?php echo $white_avg; ?>,
<?php echo $red_avg; ?>,
<?php echo $clear_avg; ?>,
<?php echo $silver_avg; ?>
]
}]
});
chart1.render();
function toolTipFormatter(e) {
var str = "";
var total = 0 ;
var str3;
var str2 ;
for (var i = 0; i < e.entries.length; i++){
var str1 = "<span style= \"color:"+e.entries[i].dataSeries.color + "\">" + e.entries[i].dataSeries.name + "</span>: <strong>"+ e.entries[i].dataPoint.y + "</strong> <br/>" ;
total = e.entries[i].dataPoint.y + total;
str = str.concat(str1);
}
str2 = "<strong>" + e.entries[0].dataPoint.label + "</strong> <br/>";
str3 = "<span style = \"color:Tomato\">Total: </span><strong>" + total + "</strong><br/>";
return (str2.concat(str)).concat(str3);
}
function toggleDataSeries(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}}
window.onload = function () {
var chart = new CanvasJS.Chart("line", {
animationEnabled: true,
zoomEnabled: true,
title:{
text: "Hot Cars Temperatures"
},
axisY:{
title: "Temperature",
lineColor: "#C24642",
tickColor: "#C24642",
labelFontColor: "#C24642",
titleFontColor: "#C24642",
includeZero: true,
suffix: "C"
},
axisX: {
title: "Time",
titleFontColor:"#369EAD",
lineColor:"#369EAD",
tickColor:"#369EAD",
labelFontColor:"#369EAD" ,
includeZero: true,
suffix: " Mins"
},
toolTip: {
shared: true
},
legend: {
cursor: "pointer",
itemclick: toggleDataSeries
},
data: [
{
type: "line",
name: "White Temperatures",
color: "#0d00ff",
showInLegend: true,
axisYIndex: 1,
dataPoints: [<?php echo $white_data; ?>]
},
{
type: "line",
name: "Red Temperatures",
color: "#ff1f1f",
axisYIndex: 0,
showInLegend: true,
dataPoints: [<?php echo $red_data; ?>]
},
{
type: "line",
name: "Clear Temperatures",
color: "#9d00ff",
axisYIndex: 0,
showInLegend: true,
dataPoints: [<?php echo $clear_data; ?>]
},
{
type: "line",
name: "Silver Temperatures",
color: "#bdbdbd",
axisYIndex: 0,
showInLegend: true,
dataPoints: [<?php echo $silver_data; ?>]
},
{
type: "line",
name: "Black Temperatures",
color: "#000000",
axisYIndex: 0,
showInLegend: true,
dataPoints: [<?php echo $black_data; ?>]
}]
});
chart.render();
function toggleDataSeries(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
e.chart.render();
}}
</script>
</head>
<body>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="line" style="height: 370px; width: 75%;"></div>
<br>
<br>
<br>
<div id="bar" style="height: 370px; width: 75%;"></div>
</body>
</html>

window.onload gets fired when the entire page loads, including its content (images, CSS, scripts, etc.). You can create any number of charts within window.onload. Refer CanvasJS documentation for tutorial on rendering multiple charts in a page.
Below is the working code.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart1 = new CanvasJS.Chart("bar", {
animationEnabled: true,
title:{
text: "Maximum, Minimum and Average Temperatures for the Hot Cars"
},
axisY: {
title: "Temperature (C)",
includeZero: true
},
legend: {
cursor:"pointer",
itemclick : toggleDataSeries
},
toolTip: {
shared: true,
content: toolTipFormatter
},
data: [{
type: "bar",
showInLegend: true,
name: "Maximum",
color: "#fc0303",
dataPoints: [
<?php echo $black_max; ?>,
<?php echo $white_max; ?>,
<?php echo $red_max; ?>,
<?php echo $clear_max; ?>,
<?php echo $silver_max; ?>
]
},
{
type: "bar",
showInLegend: true,
name: "Minimum",
color: "#0314fc",
dataPoints: [
<?php echo $black_min; ?>,
<?php echo $white_min; ?>,
<?php echo $red_min; ?>,
<?php echo $clear_min; ?>,
<?php echo $silver_min; ?>
]
},
{
type: "bar",
showInLegend: true,
name: "Average",
color: "#b503fc",
dataPoints: [
<?php echo $black_avg; ?>,
<?php echo $white_avg; ?>,
<?php echo $red_avg; ?>,
<?php echo $clear_avg; ?>,
<?php echo $silver_avg; ?>
]
}]
});
chart1.render();
var chart2 = new CanvasJS.Chart("line", {
animationEnabled: true,
zoomEnabled: true,
title:{
text: "Hot Cars Temperatures"
},
axisY:{
title: "Temperature",
lineColor: "#C24642",
tickColor: "#C24642",
labelFontColor: "#C24642",
titleFontColor: "#C24642",
includeZero: true,
suffix: "C"
},
axisX: {
title: "Time",
titleFontColor:"#369EAD",
lineColor:"#369EAD",
tickColor:"#369EAD",
labelFontColor:"#369EAD" ,
includeZero: true,
suffix: " Mins"
},
toolTip: {
shared: true
},
legend: {
cursor: "pointer",
itemclick: toggleDataSeries
},
data: [
{
type: "line",
name: "White Temperatures",
color: "#0d00ff",
showInLegend: true,
axisYIndex: 1,
dataPoints: [<?php echo $white_data; ?>]
},
{
type: "line",
name: "Red Temperatures",
color: "#ff1f1f",
axisYIndex: 0,
showInLegend: true,
dataPoints: [<?php echo $red_data; ?>]
},
{
type: "line",
name: "Clear Temperatures",
color: "#9d00ff",
axisYIndex: 0,
showInLegend: true,
dataPoints: [<?php echo $clear_data; ?>]
},
{
type: "line",
name: "Silver Temperatures",
color: "#bdbdbd",
axisYIndex: 0,
showInLegend: true,
dataPoints: [<?php echo $silver_data; ?>]
},
{
type: "line",
name: "Black Temperatures",
color: "#000000",
axisYIndex: 0,
showInLegend: true,
dataPoints: [<?php echo $black_data; ?>]
}]
});
chart2.render();
function toolTipFormatter(e) {
var str = "";
var total = 0 ;
var str3;
var str2 ;
for (var i = 0; i < e.entries.length; i++){
var str1 = "<span style= \"color:"+e.entries[i].dataSeries.color + "\">" + e.entries[i].dataSeries.name + "</span>: <strong>"+ e.entries[i].dataPoint.y + "</strong> <br/>" ;
total = e.entries[i].dataPoint.y + total;
str = str.concat(str1);
}
str2 = "<strong>" + e.entries[0].dataPoint.label + "</strong> <br/>";
str3 = "<span style = \"color:Tomato\">Total: </span><strong>" + total + "</strong><br/>";
return (str2.concat(str)).concat(str3);
}
function toggleDataSeries(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
e.chart.render();
}
}
</script>
</head>
<body>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="line" style="height: 370px; width: 75%;"></div>
<br>
<br>
<br>
<div id="bar" style="height: 370px; width: 75%;"></div>
</body>
</html>

Related

How to show values on the bar vertically in apex bar chart

I am using apex bar chart in which i want to show values on the bar vertically but it shows horizontally.
I search alot to show value vertically but not find any solution. Please help me to solve this issue. I also share the code.
Here is The script of graph:
<script type="text/javascript">
$(document).ready(function() {
// custom datalabelBar
var options = {
chart: {
height: 350,
type: 'bar',
toolbar: {
show: true
}
},
plotOptions: {
bar: {
horizontal: false,
dataLabels: {
position: 'top',
},
}
},
dataLabels: {
enabled: true,
position: 'top',
formatter: function (val) {
return val ;
},
horizontal: true,
offsetX: 0,
style: {
fontSize: '10px',
colors: ['#000']
}
},
stroke: {
show: false,
width: 1,
colors: ['#fff'],
lineCap: 'round',
curve: 'smooth',
},
series: [{
name: 'Packing',
data: <?php echo json_encode($wd_packing) ?>
}, {
name: 'Dispatch',
data: <?php echo json_encode($wd_dispatch) ?>
},
{
name: 'Remaning',
data: <?php echo json_encode($wd_reaming) ?>
}],
xaxis: {
categories: <?php echo json_encode($wd_week) ?>,
},
}
var chart = new ApexCharts(
document.querySelector("#weekly_dispatch_graph"),
options
);
chart.render();
});
Here is the screenshot of graph:
Please Help me to solve this issue. Thanks in advance.
It is possible! Your question is about dataLabels. ApexCharts give us a common dataLabels option and a dataLabels option depended on chart type. There are options.dataLabels and options.plotOptions.bar.dataLabels respectively.
In the first one you can play with offsetY and in the second one you can configure this labels orientation and their position.
Try to play with this values, good luck :)
var options = {
chart: {
type: 'bar'
},
series: [{
name: 'Packing',
data: [300000, 300000, 500000, 800000]
}, {
name: 'Dispatch',
data: [46577, 296948, 153120, 0]
},
{
name: 'Remaning',
data: [252962, 2382, 235143, 800000]
}
],
xaxis: {
categories: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
},
plotOptions: {
bar: {
dataLabels: {
orientation: 'vertical',
position: 'center' // bottom/center/top
}
}
},
dataLabels: {
style: {
colors: ['#000000']
},
offsetY: 15, // play with this value
},
}
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
<div id="chart"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts#3.18.1/dist/apexcharts.min.js"></script>
dataLabels: {
position: 'top',
enabled: true,
textAnchor: 'start',
style: {
fontSize: '10pt',
colors: ['#000']
},
offsetX: 0,
horizontal: true,
dropShadow: {
enabled: false
}
},
Note the offsetX: 0 and horizontal: true.

jqGrid with select2. In edition mode, when navigation rows, values from row is not substituted in select

var dataTable = [{
id: '10',
date_create: '27-06-2019',
department_name: 'Отдел информационных систем',
status_name: 'В очереди на выполнение',
type_work_name: 'Не работает Интернет',
phone: '99-99-99',
auditory_name: 'В-200',
inventory_number: '24274',
comment: 'something goes wrong',
extra_fields: [{
"tw_value_field_id": "4",
"tw_field_value": "Microsoft Excel",
"type_work_name_field_id": "1",
"field_name": "Название программного обеспечения",
"field_datatype": "select",
"type_work_name_field_value": "Microsoft Word:Microsoft Word;Microsoft Excel:Microsoft Excel;Microsoft PowerPoint:Microsoft PowerPoint"
},
{
"tw_value_field_id": "5",
"tw_field_value": "Problem №1",
"type_work_name_field_id": "3",
"field_name": "Примечание",
"field_datatype": "textarea",
"type_work_name_field_value": null
},
{
"tw_value_field_id": "6",
"tw_field_value": "99-99-55",
"type_work_name_field_id": "2",
"field_name": "Телефон",
"field_datatype": "input",
"type_work_name_field_value": null
}
]
},
{
id: '20',
date_create: '28-06-2019',
department_name: 'Отдел информационных систем',
status_name: 'В очереди на выполнение',
type_work_name: 'Не работает Интернет',
phone: '99-99-98',
auditory_name: 'В-201',
inventory_number: '24275',
comment: 'something goes wrong',
extra_fields: [{
"tw_value_field_id": "7",
"tw_field_value": "Microsoft PowerPoint",
"type_work_name_field_id": "1",
"field_name": "Название программного обеспечения",
"field_datatype": "select",
"type_work_name_field_value": "Microsoft Word:Microsoft Word;Microsoft Excel:Microsoft Excel;Microsoft PowerPoint:Microsoft PowerPoint"
},
{
"tw_value_field_id": "8",
"tw_field_value": "Problem №2",
"type_work_name_field_id": "3",
"field_name": "Примечание",
"field_datatype": "textarea",
"type_work_name_field_value": null
},
{
"tw_value_field_id": "9",
"tw_field_value": "88-99-55",
"type_work_name_field_id": "2",
"field_name": "Телефон",
"field_datatype": "input",
"type_work_name_field_value": null
}
]
},
{
id: '30',
date_create: '20-06-2019',
department_name: 'Подготовительное отделение',
status_name: 'В очереди на выполнение',
type_work_name: 'Переустановка ОС',
phone: '99-99-00',
auditory_name: 'В-202',
inventory_number: '24276',
comment: 'something goes wrong',
extra_fields: [{
"tw_value_field_id": "10",
"tw_field_value": "Microsoft Word",
"type_work_name_field_id": "1",
"field_name": "Название программного обеспечения",
"field_datatype": "select",
"type_work_name_field_value": "Microsoft Word:Microsoft Word;Microsoft Excel:Microsoft Excel;Microsoft PowerPoint:Microsoft PowerPoint"
},
{
"tw_value_field_id": "11",
"tw_field_value": "Problem №3",
"type_work_name_field_id": "3",
"field_name": "Примечание",
"field_datatype": "textarea",
"type_work_name_field_value": null
},
{
"tw_value_field_id": "12",
"tw_field_value": "77-99-55",
"type_work_name_field_id": "2",
"field_name": "Телефон",
"field_datatype": "input",
"type_work_name_field_value": null
}
]
}
];
$(document).ready(function () {
$("#table-application").jqGrid({
datatype: "local",
data: dataTable,
colNames: ["Номер заявки в системе", "Дата создания", "Отдел", "Статус",
"Тип работ", "Номер телефона для связи", "Аудитория", "Инвентарный номер",
"Описание проблемы", ""
],
colModel: [{
name: "id",
id: "id"
},
{
name: "date_create",
id: "date_create"
},
{
name: "department_name",
id: "department_name",
},
{
name: "status_name",
id: "status_name",
editable: true,
edittype: "select",
editoptions: {
value: "1:В очереди на выполнение;2:Принята в работу;3:Закрыта"
}
},
{
name: "type_work_name",
id: "type_work_name",
editable: true,
edittype: "select",
editoptions: {
value: "1:Установка телефона; 2:Переустановка ОС; 3:Ремонт ПК и техники; 4:Заправка/замена картриджа; 5:Не работает Интернет"
}
},
{
name: "phone",
id: "phone",
editable: true
},
{
name: "auditory_name",
id: "auditory_name",
editable: true,
edittype: "select",
editoptions: {
value: "1:В-200; 2:В-201; 3:В-202; 4:K-300"
}
},
{
name: "inventory_number",
id: "inventory_number",
editable: true,
edittype: "select",
editoptions: {
value: "1:876547; 2:453213; 3:342123; 4:567496; 5:409325; 6:24274; 7:24275; 8:24276",
dataInit: function (el) {
$(el).select2({
language: 'ru',
width: '100%'
});
}
}
},
{
name: "comment",
id: "comment",
editable: true,
edittype: "textarea"
},
{
name: "extra_fields",
id: "extra_fields",
classes: "extra-field",
hidden: true,
title: false,
editable: false,
jsonmap: "extra_fields",
formatter: function (cellvalue) {
if (cellvalue != null) {
return JSON.stringify(cellvalue);
} else
return cellvalue;
}
}
],
pager: "#pager",
height: "auto",
autowidth: true,
forceFit: true,
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
caption: "Список заявок",
rownumbers: true,
subGrid: true,
subGridBeforeExpand: function (pID, id) {
//получаем значение поля extra_fields по id выбранной строки
extra_field_val = $('#table-application').jqGrid('getCell', id, 'extra_fields');
var jsonArray = $.parseJSON(extra_field_val);
//если дополнительная информация по заявке есть, раскрываем список
if (jsonArray.length > 0) {
console.log(true);
return true;
}
return false;
},
subGridRowExpanded: function (subgrid_id, row_id) {
var subgrid_table_id;
subgrid_table_id = subgrid_id + "_t";
jQuery("#" + subgrid_id).html("<table id='" + subgrid_table_id +
"' class='scroll'></table>");
extra_field_val = $('#table-application').jqGrid('getCell', row_id,
'extra_fields');
var response = $.parseJSON(extra_field_val);
//задаем массив для подтаблицы
var element_name, element_mode, col_name, objData;
var subColNames, subColModel, subData, selectValue;
subColNames = [];
subColModel = [];
subData = [];
objData = {};
for (var i = 0; i < response.length; i++) {
element_name = {};
element_name = response[i]['field_name'];
subColNames.push(element_name);
element_mode = {};
element_mode = {
name: "col_" + response[i]['tw_value_field_id'],
id: "col_" + response[i]['tw_value_field_id'],
editable: true
};
subColModel.push(element_mode);
if (response[i]['field_datatype'] == 'select') {
element_mode['edittype'] = "select";
selectValue = response[i]['type_work_name_field_value'];
element_mode['editoptions'] = {
value: selectValue
};
}
col_name = "col_" + response[i]['tw_value_field_id'];
objData[col_name] = response[i]['tw_field_value'];
}
subColNames.push("");
subColModel.push({
name: "id",
id: "id",
hidden: true,
editable: true,
editrules: {
edithidden: false
}
});
console.log(subColModel);
objData['id'] = response[0]['id'];
subData.push(objData);
var lastSel;
jQuery("#" + subgrid_table_id).jqGrid({
datatype: "local",
data: subData,
colNames: subColNames,
colModel: subColModel,
height: '75%',
caption: "Дополнительная информация",
onSelectRow: function (id) {
if (id && id !== lastSel) {
jQuery("#" + subgrid_table_id).restoreRow(lastSel);
lastSel = id;
}
jQuery("#" + subgrid_table_id).editRow(id, true);
},
editurl: 'clientArray'
});
},
editurl: 'clientArray'
});
$("#table-application").navGrid("#pager", {
edit: true,
add: false,
del: false,
search: false,
refresh: false,
editicon: "none",
edittext: "Редактировать",
}, {
/*hier setting of edit form*/
});
});
.ui-jqgrid {
font-size: 12px;
}
table {
table-layout: fixed;
}
table th,
table td {
word-wrap: break-word;
}
.table-light tbody+tbody,
.table-light td,
.table-light th,
.table-light thead th {
border-color: #b8c3c3;
}
th.ui-th-column div {
white-space: normal !important;
height: auto !important;
padding: 2px;
}
.ui-jqdialog-content .FormGrid {
margin: 0;
overflow: inherit;
}
.ui-jqdialog .ui-jqdialog-titlebar {
height: 30px;
}
.fm-button {
height: auto;
}
.ui-jqgrid .ui-jqgrid-titlebar {
height: 25px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jqGrid Edit Rows Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<link rel="stylesheet" href=" https://js.kintone.com/jqgrid/v5.4.0/css/ui.jqgrid.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<script src="https://js.kintone.com/jqgrid/v5.4.0/js/i18n/grid.locale-ru.js"></script>
<script src="https://js.kintone.com/jqgrid/v5.4.0/js/jquery.jqGrid.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<div id="grid_container" class="mt-5">
<table id="table-application">
<tr>
<td></td>
</tr>
</table>
<div id="pager"></div>
</div>
</div>
</div>
</div>
</body>
</html>
I use together jqGrid and select2. In edition mode, when navigation rows, values from row is not substituted in select. If I click button with arrow "next" or "previous" value of inputs, textarea are changed but value of select are not changed.
This happens if I use select2, without select2 it works right. How can I fix it go on using select2?
setting select2 is below
{name: "status_name", id: "status_name", editable: true, edittype: "select", editoptions: {
dataUrl:"/Operator/OperatorApplicationController/getSelect&table=status",
dataInit: function (el) {
$(el).select2({
language: 'ru',
width: '100%'
});
}}}
Since the select2 is external plugin used in jqGrid, maybe you will need to refresh its value when the prev/next button is click.
I have never try this, but you can use the afterclickPgButtons for the form edit button click event - see docs here and undocumented change event in select2 - see here
This can look like this
$('#grid'). jqGrid('navGrid', pager, {params},
...
{ afterclickPgButtons : function(button, form, id ) {
$("#status_name").val(null).trigger('change.select2');
},...
} // edit options parameter
);
Mybe you will need to check if the id of the element is correct.

loadData just won't work

Below is my complete code. There are no errors and Directory is empty is shown.
<script>
$(document).ready(function() {
$("#table").jsGrid({
width: "100%",
height: "auto",
paging: false,
autoload: false,
noDataContent: "Directory is empty",
controller: {
loadData: function(filter) {
var data = {
data: [{
nickname: "test",
email: "t#gmail.com"
}]
};
console.log(data);
return data;
}
},
fields: [{
name: "nickname",
type: "text",
width: 80,
title: "Name"
}, {
name: "email",
type: "text",
width: 100,
title: "Email Address",
readOnly: false
}]
});
});
</script>
The console output is as below. Is there anything incorrect about the formatting?
Is there a way to enable more diagnostics, like printing out what data it is actually receiving so as to allow troubleshooting?
You need to set autoload:true
autoload (default false)
A boolean value specifying whether controller.loadData will be called when grid is rendered.
And also you need to return data.data inside of loadData() mehtod because you have array inside of data.
CODE SNIPPET
controller: {
loadData: function(filter) {
var data = {
data: [{
nickname: "test",
email: "t#gmail.com"
}]
};
return data.data; //As per your data array is like this console.log(data.data) so you need to send like this data.data
}
},
DEMO
$(document).ready(function() {
$("#table").jsGrid({
width: "100%",
height: "auto",
paging: false,
//for loadData method Need to set auto load true
autoload: true,
noDataContent: "Directory is empty",
controller: {
loadData: function(filter) {
alert('Table load data method fire because we have set config autoload:true')
var data = {
data: [{
nickname: "test",
email: "t#gmail.com"
}]
};
return data.data;//As per your data array is like this console.log(data.data) so you need to send like this data.data
}
},
fields: [{
name: "nickname",
type: "text",
width: 80,
title: "Name"
}, {
name: "email",
type: "text",
width: 100,
title: "Email Address",
readOnly: false
}]
});
$("#table1").jsGrid({
width: "100%",
height: "auto",
paging: false,
//for loadData method will not work with auto load false
autoload: false,
noDataContent: "Directory is empty",
controller: {
loadData: function(filter) {
alert('Table 1 load data method not fire')
return []
}
},
fields: [{
name: "nickname",
type: "text",
width: 80,
title: "Name"
}, {
name: "email",
type: "text",
width: 100,
title: "Email Address",
readOnly: false
}]
});
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<div id="table"></div>
<br>
<br>
<br>
<div id="table1"></div>

Kendo batch editing with entire grid edit mode

I have implemented kendo grid batch editing feature to my application. I am able to save the changes by the default functionality provided by kendo. Here is the same code I have implemented in my project:
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/grid/editing">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.flat.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.flat.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.3.1026/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/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").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120, editor: customBoolEditor },
{ command: "destroy", title: " ", width: 150 }],
editable: true
});
});
function customBoolEditor(container, options) {
var guid = kendo.guid();
$('<input class="k-checkbox" id="' + guid + '" type="checkbox" name="Discontinued" data-type="boolean" data-bind="checked:Discontinued">').appendTo(container);
$('<label class="k-checkbox-label" for="' + guid + '">​</label>').appendTo(container);
}
</script>
</div>
</body>
</html>
I need a feature to show the entire grid in edit mode have all the editable column with edit templates. I tried to add same client template as editor template but the behavior is not as expected. Is there any way to show both client template and editor template with a common template?
For e.g.
In the above example, I need Unit Price with numeric textbox present on all the rows. Not only when I click to it.
Here has an example;
$("#grid").kendoGrid({
dataSource: {
schema: {
model: {
id: "id",
fields: {
id: { editable: false }
}
}
},
change: function() {
$("textarea").val(
kendo.stringify(this.view())
);
},
data: [
{ id:1, age: 30, name: "John Doe" }
]
},
columns: [
{ field: "id", width: 50 },
{ field: "age", template: "<input data-bind='value: age' data-role='numerictextbox'>" },
{ field: "name", template:"<input data-bind='value: name' >" }
],
dataBound: function() {
var rows = this.tbody.children();
var dataItems = this.dataSource.view();
for (var i = 0; i < dataItems.length; i++) {
kendo.bind(rows[i], dataItems[i]);
}
}
});
http://jsbin.com/ApoFobA/2/edit?html,js,output

Based on selection is it possible to change value axis

I have a requirement i.e based on the tree view check box selection the value axis need to update.I am using 4 check boxes with 4 value axis.when ever I check the first item corresponding value axis should be changed .3 other axis should in invisible state.
Here I tried with some of the code and updated .
Code:
<div id="treeview"></div>
<div id="example" class="k-content">
<div class="chart-wrapper">
<div id="chart"></div>
</div>
</div>
var valueAxes = [
{ name: "KM",visible:false,
title: { text: "KM" ,visible:false}
},
{ name: "Miles Per Gallon",
title: { text: "Miles Per Gallon" }
},
{
name: "Miles",
title: { text: "Miles " }
},
{
name: "liters per 100km",
title: { text: "liters per 100km" }
}
];
function createChart() {
$("#chart").kendoChart({
legend: {
position: "top"
},
series: [{
type: "column",
data: [20, 40, 45, 30, 50],
stack: true,
name: "on battery",
color: "#003c72"
}, {
type: "column",
data: [20, 30, 35, 35, 40],
stack: true,
name: "on gas",
color: "#0399d4"
}, {
type: "area",
data: [30, 38, 40, 32, 42],
name: "mpg",
color: "#642381"
}, {
type: "area",
data: [7.8, 6.2, 5.9, 7.4, 5.6],
name: "l/100 km",
color: "#e5388a"
}],
valueAxes:valueAxes,
categoryAxis: {
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
axisCrossingValues: [0, 0, 10, 10]
}
});
}
$(document).ready(function() {
createChart();
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true
},
dataSource: [{
id: 1,
text: "Value axis",
expanded: true,
items: [{
id: 2,
text: "KM"
},
{
id: 3,
text: "Miles Per Gallon"
},
{
id: 4,
text: "Miles "
},
{
id: 5,
text: "liters per 100km"
}]
}]
}).data("kendoTreeView");
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
$("#treeview").find(":checked").each(function() {
var nodeText =$(this).parent().parent().text();
$.each(valueAxes, function(index, valueAxes) {
if (valueAxes.name == nodeText) {
checkedSeries.push(valueAxes);
checkedSeries.visible==="true";
checkedSeries.title.visible===true;
}
});
});
chart.options.valueAxes = checkedSeries;
chart.refresh();
});
});
jsbin: Value axis change
Yes , it is possible to bind and unbind value axis and series at a time.
Change your scripts like below
var valueAxes = [
{
name: "KM", labels: {
format: "{0}"
}, min: 0,
max: 9,
title: { text: "KM" }
},
{
name: "Miles Per Gallon", labels: {
format: "{0}%"
}, min: 0,
max: 5,
title: { text: "Miles Per Gallon" }
},
{
name: "Miles", labels: {
format: "{0}%"
},
title: { text: "Miles " }
},
{
name: "liters per 100km", min: 0,
max: 1,
title: { text: "liters per 100km" }
}];
var series = [{
type: "column",
axis: "KM",
data: [20, 40, 45, 30, 50],
stack: true,
name: "KM",
color: "#003c72"
}, {
type: "column",
data: [20, 30, 35, 35, 40],
axis: "Miles Per Gallon",
stack: true,
name: "Miles Per Gallon",
color: "#0399d4"
}, {
type: "column",
data: [30, 38, 40, 32, 42],
axis: "Miles",
name: "Miles",
color: "#642381"
}, {
type: "column",
axis: "liters per 100km",
data: [7.8, 6.2, 5.9, 7.4, 5.6],
name: "liters per 100km",
color: "#e5388a"
}];
function createChart(inputValueAxes, inputSeries) {
$("#chart").kendoChart({
legend: {
position: "top"
},
series: inputSeries,
valueAxes: inputValueAxes,
categoryAxis: {
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
axisCrossingValues: [0, 0, 10, 10]
}
});
}
$(document).ready(function () {
createChart(valueAxes, series);
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true
},
dataSource: [{
id: 1,
text: "Value axis",
expanded: true,
items: [{
id: 2,
text: "KM"
},
{
id: 3,
text: "Miles Per Gallon"
},
{
id: 4,
text: "Miles "
},
{
id: 5,
text: "liters per 100km"
}]
}]
}).data("kendoTreeView");
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
var checkedAxes = [];
if ($("#treeview").find(":checked").length !== 0) {
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(valueAxes, function (index, valueAxes) {
if (valueAxes.name == nodeText.trim()) {
checkedAxes.push(valueAxes);
checkedAxes.visible = true;
}
});
$.each(series, function (index, series) {
if (series.name == nodeText.trim()) {
checkedSeries.push(series);
}
});
});
createChart(checkedAxes, checkedSeries);
}
else {
createChart(checkedAxes, checkedSeries);
}
});
});
Refer this http://jsbin.com/eyibar/49/edit
For convenience, Intially i load all the chart axeses. Its working as you asked....
jsbin: http://jsbin.com/eyibar/37/edit
<html>
<head>
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.rtl.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.dataviz.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.mobile.all.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.1.319/js/kendo.all.min.js"></script>
<meta charset="utf-8" />
<title>JS Bin</title>
<style>
#chart { width: 600px; }
</style>
</head>
<body>
<div id="treeview"></div>
<div id="example" class="k-content">
<div class="chart-wrapper">
<div id="chart"></div>
</div>
</div>
<script type="text/javascript">
var valueAxes = [
{
name: "KM",
title: { text: "KM" }
},
{
name: "Miles Per Gallon",
title: { text: "Miles Per Gallon" }
},
{
name: "Miles",
title: { text: "Miles " }
},
{
name: "liters per 100km",
title: { text: "liters per 100km" }
}];
function createChart(valueAxes) {
$("#chart").kendoChart({
legend: {
position: "top"
},
series: [{
type: "column",
data: [20, 40, 45, 30, 50],
stack: true,
name: "on battery",
color: "#003c72"
}, {
type: "column",
data: [20, 30, 35, 35, 40],
stack: true,
name: "on gas",
color: "#0399d4"
}, {
type: "area",
data: [30, 38, 40, 32, 42],
name: "mpg",
color: "#642381"
}, {
type: "area",
data: [7.8, 6.2, 5.9, 7.4, 5.6],
name: "l/100 km",
color: "#e5388a"
}],
valueAxes: valueAxes,
categoryAxis: {
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
axisCrossingValues: [0, 0, 10, 10]
}
});
}
$(document).ready(function () {
createChart(valueAxes);
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true
},
dataSource: [{
id: 1,
text: "Value axis",
expanded: true,
items: [{
id: 2,
text: "KM"
},
{
id: 3,
text: "Miles Per Gallon"
},
{
id: 4,
text: "Miles "
},
{
id: 5,
text: "liters per 100km"
}]
}]
}).data("kendoTreeView");
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
if ($("#treeview").find(":checked").length != 0) {
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(valueAxes, function (index, valueAxes) {
if (valueAxes.name == nodeText.trim()) {
checkedSeries.push(valueAxes);
checkedSeries["visible"] = true;
}
});
});
createChart(checkedSeries);
}
else {
createChart(checkedSeries);
}
});
});
</script>
</body>
</html>
I edited your code in that I can able to bind and unbind the valueaxis by calling the creatChart(checkedAxes) function in if condition with length==-1,at that time the series is not updated.
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
var checkedAxes = [];
if ($("#treeview").find(":checked").length !== -1){
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(valueAxes, function (index, valueAxes) {
if (valueAxes.name == nodeText) {
checkedAxes.push(valueAxes);
checkedAxes.visible = true;
}
});
$.each(series, function (index, series) {
if (series.name == nodeText) {
checkedSeries.push(series);
}
});
});
chart.options.series = checkedSeries;
chart.options.valeAxes = checkedAxes;
chart.refresh();
}
createChart(checkedAxes);
});
but if I tried by without calling the creatChart(checkedAxes) function,the series binded to the chart are updated.
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
var checkedAxes = [];
if ($("#treeview").find(":checked").length !== -1){
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(valueAxes, function (index, valueAxes) {
if (valueAxes.name == nodeText) {
checkedAxes.push(valueAxes);
checkedAxes.visible = true;
}
});
$.each(series, function (index, series) {
if (series.name == nodeText) {
checkedSeries.push(series);
}
});
});
chart.options.series = checkedSeries;
chart.options.valeAxes = checkedAxes;
chart.refresh();
}
});
I didn't get the both scenarios at a time.sorry,hope you find the solution.
Cheers,
Happy Coding...

Resources