Filter key-value-list with text input Handsontable - handsontable

first of all thank you for your time.
i need your help with handsontable (page oficial, documentation) . i am trying to create a filter for a custom type cell. key-value-list but i can only “filter” the already rendered data and i can’t re-render more data to always show all filtered data.
here is an example code
https://jsfiddle.net/crifesma/nusahc7p/50/
function BuscarEnSelect_hot(elemento) {
var text = $(elemento.TEXTAREA).val().toLowerCase();
if (text == "") {
for (item of elemento.htEditor.table.rows) {
item.hidden = false;
}
} else {
for (item of elemento.htEditor.table.rows) {
if (item.innerText.toLowerCase().includes(text)) {
item.hidden = false;
} else {
item.hidden = true;
}
}
}
}
/**
* The cell type adds supports for displaing the label value except the key in the key-value
* dropdown editor type.
*/
class KeyValueListEditor extends Handsontable.editors.HandsontableEditor {
prepare(row, col, prop, td, value, cellProperties) {
super.prepare(row, col, prop, td, value, cellProperties);
Object.assign(this.htOptions, {
licenseKey: 'non-commercial-and-evaluation',
data: this.cellProperties.source,
columns: [
{
data: '_id',
},
{
data: 'label',
},
],
hiddenColumns: {
columns: [1],
},
colWidths: cellProperties.width - 1,
beforeValueRender: function (value, {
row,
instance
}) {
return instance.getDataAtRowProp(row, 'label');},
beforeValueRender(value, { row, instance }) {
return instance.getDataAtRowProp(row, 'label');
},
});
if (cellProperties.keyValueListCells) {
this.htOptions.cells = cellProperties.keyValueListCells;
}
if (this.htEditor) {
this.htEditor.destroy();
}
this.htEditor = new Handsontable(this.htContainer, this.htOptions);
this.htEditor.rootElement.style.overflowX = "hidden";
//this.htEditor.rootElement.style.overflowY = "scroll";
this.htEditor.rootElement.style.height = this.htOptions.data.length < 11 ? td.clientHeight * this.htOptions.data.length + 7 + "px" : td.clientHeight * 10 + "px";
this.htEditor.rootElement.style.border = "1px solid #151414";
var w_alto = $(window).height();
var td_position = $(this.TD).offset();
this.htEditor.container.childNodes[0].style.width = td.clientWidth + "px";
this.htEditor.container.childNodes[0].style.maxWidth = td.clientWidth + "px";
this.htEditor.rootElement.style.maxWidth = td.clientWidth + "px";
if ((w_alto - td_position.top) < (td.clientHeight * 11)) {
this.htEditor.rootElement.style.top = ((td.clientHeight * 11) + 4) * -1 + "px"; //el + 2 es por los bordes
} else {
this.htEditor.rootElement.style.top = "";
}
var ddl = this;
$("textarea.handsontableInput").on("input", function (e) {
BuscarEnSelect_hot(ddl);
});
}
setValue(value) {
if (this.htEditor) {
const index = this.htEditor.getDataAtProp('_id').findIndex(id => id === value);
if (index !== -1) {
value = this.htEditor.getDataAtRowProp(index, 'label');
}
}
super.setValue(value);
}
getValue() {
const value = super.getValue();
if (this.htEditor) {
const labels = this.htEditor.getDataAtProp('label');
const row = labels.indexOf(value);
if (row !== -1) {
return this.htEditor.getDataAtRowProp(row, '_id');
}
}
return value;
}
}
const keyValueListValidator = function(value, callback) {
let valueToValidate = value;
if (valueToValidate === null || valueToValidate === void 0) {
valueToValidate = '';
}
if (this.allowEmpty && valueToValidate === '') {
callback(true);
} else {
callback(this.source.find(({ _id }) => _id == value) ? true : false);
}
};
const keyValueListRenderer = function(hot, TD, row, col, prop, value, cellProperties) {
const item = cellProperties.source.find(({
_id
}) => _id === value);
if (item) {
value = item.label;
}
Handsontable.renderers.getRenderer('autocomplete').call(hot, hot, TD, row, col, prop, value, cellProperties);
};
Handsontable.cellTypes.registerCellType('key-value-list', {
editor: KeyValueListEditor,
validator: keyValueListValidator,
renderer: keyValueListRenderer,
});
const example = document.getElementById('example');
const hot = new Handsontable(example, {
data: Handsontable.helper.createSpreadsheetData(10, 10),
colWidths: 100,
width: '100%',
height: 320,
rowHeights: 23,
rowHeaders: true,
colHeaders: true,
afterChange(changes) {
if (!changes) {
return;
}
console.log(this.getDataAtCell(changes[0][0], changes[0][1]));
},
type: 'key-value-list',
source: [
{_id: 1, label: '101 | Mike'},
{_id: 2, label: '102 | Roman'},
{_id: 3, label: '103 | Juan'},
{_id: 4, label: '104 | Mike'},
{_id: 5, label: '105 | Roman'},
{_id: 6, label: '106 | Juan'},
{_id: 7, label: '107 | Mike'},
{_id: 8, label: '108 | Roman'},
{_id: 9, label: '109 | Juan'},
{_id: 10, label: '110 | Mike'},
{_id: 11, label: '111 | Roman'},
{_id: 12, label: '112 | Juan'},
{_id: 13, label: '113 | Mike'},
{_id: 14, label: '114 | Roman'},
{_id: 15, label: '115 | Juan'},
{_id: 16, label: '116 | Mike'},
{_id: 17, label: '117 | Roman'},
{_id: 18, label: '118 | Juan'},
{_id: 19, label: '119 | Mike'},
{_id: 20, label: '120 | Roman'},
{_id: 21, label: '121 | Juan'},
]
});
.wtHider{
width:200px !important;
}
.handsontableInputHolder .wtSpreader .htCore{
width:200px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/handsontable#latest/dist/handsontable.full.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/handsontable#latest/dist/handsontable.full.min.css" />
<div id="example"></div>

Related

How to sort time column in jsgrid?

We are binding a table using jqgrid. We have the first column start as a time column with a 12-hour format. We are facing an issue with sorting this data. The data is sorted correctly but it is not taking am/pm into consideration. Below is our code for binding the jqgrid:
var newFieldsArray =
[
{ name: "ID", title: "ID", type: "number", width: "50px", visible: false },
{
name: "TimeStart", title: "Start", type: "customTime", width: "100px", validate: "required",
sorttype: "date",
formatter : {
date : {
AmPm : ["am","pm","AM","PM"],
}
},
// datefmt: "m/d/Y h:i A",
//sorttype: 'datetime', formatter: 'date', formatoptions: {newformat: 'd/m/y', srcformat: 'Y-m-d H:i:s'},
insertTemplate: function () {
var $result = jsGrid.fields.customTime.prototype.insertTemplate.call(this); // original input
$result.val(varendTime);
return $result;
},
itemTemplate: function (value, item) {
return "<b style='display:none'>" + Date.parse(item.StartDate) + "</b><span>" + (item.TimeStart) + "</span>";
}
},
{
name: "TimeEnd", title: "End", type: "customTime", width: "100px", validate: "required",sorttype: "date", datefmt: "h:i"
},
{ name: "TimeTotal", title: "Time", type: "text", width: "50px", readOnly: true },
{
name: "CoilPO", title: "Coil PO", type: "text", width: "50px", validate: "required",
insertTemplate: function () {
var $result = jsGrid.fields.text.prototype.insertTemplate.call(this); // original input
$result.val(varlot);
return $result;
}
},
{ name: "Joints", title: "Joints", type: "integer", width: "60px" },
{ name: "CommercialGrade", title: "Commercial Grade", type: "integer", width: "80px" },
{ name: "QAHold", title: "QA Hold", type: "integer", width: "60px" },
{ name: "Rejected", title: "Reject", type: "integer", width: "60px" },
{ name: "ActionTaken", title: "Reason of Delay / Action Taken", type: "text", width: "120px" },
{
name: "ClassId", title: "Class",
type: "select", items: classDataArr,//classData.filter(function(n){return classdt.indexOf(n.Id) != -1 }),//classData,
valueField: "Id", textField: "Title",
insertTemplate: function () {
debugger;
var taxCategoryField = this._grid.fields[12];
var $insertControl = jsGrid.fields.select.prototype.insertTemplate.call(this);
var classId = 0;
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-insert").empty().append(taxCategoryField.insertTemplate());
$insertControl.on("change", function () {
debugger;
var classId = parseInt($(this).val());
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-insert").empty().append(taxCategoryField.insertTemplate());
});
return $insertControl;
},
editTemplate: function (value) {
var taxCategoryField = this._grid.fields[12];
var $editControl = jsGrid.fields.select.prototype.editTemplate.call(this, value);
var changeCountry = function () {
var classId = parseInt($editControl.val());
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-edit").empty().append(taxCategoryField.editTemplate());
};
debugger;
$editControl.on("change", changeCountry);
changeCountry();
return $editControl;
}
},
{
name: "VoiceId", title: "Voice", type: "select", items: voiceData,
valueField: "Id", textField: "Title", width: "120px", validate: "required",
insertcss: "tax-insert",
editcss: "tax-edit",
itemTemplate: function (teamId) {
var t = $.grep(voiceData, function (team) { return team.Id === teamId; })[0].Title;
return t;
},
},
{ name: "Remarks", title: "Remarks", type: "text", width: "110px" },
{ name: "control", type: "control" }
];
hoursGrid.jsGrid("option", "fields", newFieldsArray);
Below is two screenshots of data that appear when we sort:
Can someone tell me what we are doing wrong?
You're mixing up jsGrid and jqGrid. The way to achieve it in jsGrid is using the built-in sorter jsGrid.sortStrategies.date, I added an example below.
As commented by #Tomy Tomov (the creator of jqGrid), you're using jsGrid, not jqGrid. This is evident both by your code and by the UI in the screenshot.
Specifically, you took the date sorter of jqGrid and used it in your jsGrid code, but (of course) it's not supported there. You can go ahead and look in jsGrid source for AmPm which you used - and see it's not there.
So how to do it in jsGrid?
Just pass the built-in sorter jsGrid.sortStrategies.date to the sorter property. However, it does require Date objects, so if you only got time strings, you'll have to convert those to dates.
Below is a quick demo (jsfiddle), click the date column title to sort:
Note that getData gets a function parameter that is responsible to get all data as Date objects, and that the value of isUTC depends on whether you actually use it
$(document).ready(function () {
const dataFunc = getDataTimes;
$("#jsGrid").jsGrid({
width: "100%",
data: getData(dataFunc),
sorting: true,
fields: [{
name: "name",
type: "text",
width: 50
}, {
name: "date",
type: "date",
width: 50,
sorter: jsGrid.sortStrategies.date,
cellRenderer: (value, item) => {
const withYear = false;
const isUTC = dataFunc == getDataTimes;
return renderDateTime(value, item, withYear, isUTC);
}
}
]
});
});
function getData(getDates) {
const data = [
{name: "a"}, {name: "b"}, {name: "c"},
{name: "d"}, {name: "e"}, {name: "f"},
];
const dates = getDates();
for (let i = 0; i < dates.length; i++) {
data[i].date = dates[i];
}
return data;
}
function getDataDates() {
const date1 = new Date(2022, 10, 1, 4, 50);
const date2 = new Date(2022, 10, 1, 8, 50);
const date3 = new Date(2022, 10, 1, 15, 50);
const date4 = new Date(2021, 10, 1, 4, 50);
const date5 = new Date(2021, 10, 1, 8, 50);
const date6 = new Date(2021, 10, 1, 15, 50);
return [date1, date2, date3, date4, date5, date6];
}
function getDataTimes() {
const time1 = "3:50 AM";
const time2 = "8:50 AM";
const time3 = "4:50 AM";
const time4 = "3:50 PM";
const time5 = "8:50 PM";
const time6 = "4:50 PM";
const times = [time1, time2, time3, time4, time5, time6];
return times.map(t => convertTime12to24(t));
}
function convertTime12to24(time12h) {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return new Date(Date.UTC(2022,0,1,hours, minutes));
}
function renderDateTime(value, row, withYear, isUTC) {
return `<td>${getDateTimeAsString(value, withYear, isUTC)}</td>`;
}
function getDateTimeAsString(date, withYear, isUTC) {
var options = {
hour: 'numeric',
minute: 'numeric',
hour12: true
};
if (withYear) {
options.withYear = 'numeric';
}
if (isUTC) {
options.timeZone = 'UTC';
}
return date.toLocaleString('en-US', options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" rel="stylesheet">
<div id="jsGrid" class="jsgrid"></div>
Let me give it a try, we have 2 options to perform Sorting operation in JsGrid:
1.Custom Field (Topic Name you can refer below link)
Reference Link :http://js-grid.com/docs/#grid-fields
In this, you can define custom property in your config and extend it.
You can use sorter property and call your user defined function werein you can logic to sort date with time stamps directly.
2.Sorting Strategies (Topic Name you can refer below link)
Reference Link :http://js-grid.com/docs/#grid-fields
In this, you can create your custom objects and then apply sorting strategies of date directly on to the object to perform sorting operation as per your logic.

Feeding highchart with x and y values from ajax

I'm trying to feed my highchart from a database using ajax. From my ajax request, I want to return both x and y values (the x value is like that: year-week, ie 2020-16; the y value is a random number). My chart remains blank, I have a silent error that I cannot figure out. I'm pretty sure it comes from the strucure of the data returned by ajax, but I can't seem to fix it on my own.
Here's my javascript:
var weekOptions = {
chart: {
renderTo: 'weekContainer',
type: 'column',
},
title: {
text: 'Last 52 weeks',
},
credits: {
enabled: false,
},
xAxis: {
lineWidth: .5,
tickWidth: 1,
tickLength: 10,
},
yAxis: {
title: {
text: 'Distance (miles)'
},
labels: {
formatter: function() {
return this.value;
},
},
allowDecimals: false,
gridLineWidth: 1,
},
tooltip: {
crosshairs: true,
split: true,
useHTML: true,
valueDecimals: 2,
valueSuffix: ' miles',
formatter: '',
},
plotOptions: {
spline: {
marker: {
symbol: "circle",
radius: 3,
}
}
},
lang: {
noData: "No Data. Make sure at least one activity type is selected."
},
noData: {
style: {
fontWeight: 'bold',
fontSize: '15px',
color: '#303030'
}
},
exporting: {
buttons: {
contextButton: {
menuItems: ['viewFullscreen']
}
},
},
series: [{}],
};
//get series from ajax filtered by activity types
$.ajax({
url: "weekGetSeries.php",
type: "POST",
data: {
activityType: activityTypeSelected,
dataToDisplay: dataToDisplay,
},
dataType: "JSON",
success: function (json) {
weekOptions.series = json;
var chart = new Highcharts.Chart(weekOptions);
}
});
And here my ajax php file:
<?php
require 'dbConnection.php';
$activityType = array(1,2,3,4,5);
$dataToDisplay = "distance";
$startingDate = date('Y-m-d', strtotime('-52 week', time()));
$firstWeek = strtotime($startingDate);
$conditionActivityType = ' WHERE startingTime >= "' . $startingDate . '" AND (type=' . implode(" OR type=",$activityType) . ')';
$dataSerie = array("name" => "Weekly Stats","data" => array());
for($i = 0; $i < 52; $i++){
$nextWeek = strtotime('+'.$i.' week', $firstWeek);
$dataSerie["data"][date("o",$nextWeek) . "-" . date("W",$nextWeek)] = 0;
}
$getActivities = $conn->query("SELECT * FROM activity" . $conditionActivityType . " ORDER BY startingTime ASC");
if ($getActivities->num_rows > 0) {
while($row = $getActivities->fetch_assoc()) {
$date = substr($row["startingTime"],0,10);
$date = strtotime($date);
$week = date("W",$date);
$category = date("Y-",$date).$week;
$distance = ($row["distance"]);
$movingTime = $row["movingTime"];
$elapsedTime = $row["elapsedTime"];
$totalElevationGain = ($row["totalElevationGain"])*3.28084;
switch ($dataToDisplay) {
//distance
case "distance":
$dataSerie["data"][$category] += $distance;
break;
//Moving Time
case "movingTime":
break;
//Elapsed Time
case "elapsedTime":
break;
//elevation gain
case "totalElevationGain":
break;
//number activities
case "activities":
break;
}
}
};
$data = array();
array_push($data,$dataSerie);
echo json_encode($data);
?>
My ajax returns this:
[{"name":"Weekly Stats","data":{"2019-17":13184.4,"2019-18":73560.2,"2019-19":36899.4,"2019-20":0,"2019-21":38691.3,"2019-22":165127.8,"2019-23":188163.2,"2019-24":12888.5,"2019-25":60011.3,"2019-26":32585.2,"2019-27":12952.8,"2019-28":7944.8,"2019-29":79258.3,"2019-30":60885.2,"2019-31":0,"2019-32":0,"2019-33":0,"2019-34":0,"2019-35":0,"2019-36":0,"2019-37":30974.6,"2019-38":7766.5,"2019-39":7685,"2019-40":21128.7,"2019-41":28996,"2019-42":46362.6,"2019-43":0,"2019-44":0,"2019-45":63694.8,"2019-46":81551.1,"2019-47":104595.9,"2019-48":18121.7,"2019-49":18691.6,"2019-50":37538,"2019-51":40671.8,"2019-52":22109.6,"2020-01":22079,"2020-02":22086.7,"2020-03":21933.2,"2020-04":30702.1,"2020-05":58259,"2020-06":38811.3,"2020-07":43754,"2020-08":45109.1,"2020-09":50870.1,"2020-10":62917.8,"2020-11":0,"2020-12":95912.5,"2020-13":20836.2,"2020-14":25293,"2020-15":110540.5,"2020-16":150804.9}}]
How do I structure my data so I can feed my chart?
In your case series.data needs to be an array of arrays or an array of objects. Now it is an object.
data: [
[0, 6],
[1, 2],
[2, 6]
]
Or:
data: [{
x: 1,
y: 9
}, {
x: 1,
y: 6
}]
Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4977/
API Reference: https://api.highcharts.com/highcharts/series.column.data

Plot two lines on same month with different dates with Base-unit :month

I am developing a chart on Kendo-UI, where we need to plot a vertical line w.r.t dates available on the x-axis. The challenge, that I am facing is my x-axis contains BaseUnit: months. when I am plotting bands w.r.t two different dates in the same month, the system generates vertical line but captures a complete month section rather than plotting two different lines in the same month.
Sample Code:
var DateRange = [];
var PlotData = [];
var AllData = [];
function BindDates() {
for (var startmonth = 01; startmonth <= 12; startmonth++) {
for (var startday = 01; startday <= 30; startday++) {
DateRange.push(new Date("2019/" + startmonth + "/" + startday));
AllData.push(Math.floor((Math.random() * startday) * new Date().getMilliseconds()));
}
for (var Initial = 1; Initial <= 3; Initial++) {
var data = null;
if (Initial == 1) {
data = { from: new Date("2019/02/03"), to: new Date("2019/02/03"), color: "red", width: 0.1 };
}
else if (Initial == 2) {
data = { from: new Date("2019/05/03"), to: new Date("2019/05/03"), color: "green", width: 0.1 };
}
else if (Initial == 3) {
data = { from: new Date("2019/06/03"), to: new Date("2019/06/03"), color: "black", width: 0.1 };
}
PlotData.push(data);
}
}
createChart(DateRange, AllData, PlotData);
}
function createChart(datesss, alldata, PlotData) {
$("#chart").kendoChart({
title: {
text: "Chart Title"
},
legend: {
position: "bottom"
},
seriesDefaults: {
type: "area",
area: {
line: {
style: "smooth"
}
}
},
series: [
{
name: "Late",
color: "orange",
data: alldata
}, {
type: "line",
dashType: "dashDot",
name: "Est DT",
color: "grey",
data: alldata
},
{
name: "On time",
color: "blue",
data: alldata
}],
valueAxis: {
labels: {
format: "{0}"
},
line: {
visible: false
},
axisCrossingValue: -10
},
categoryAxis: {
type: "date",
categories: datesss,
baseUnit: "months",
labels: {
dateFormats: {
months: "MMM-yy"
}
},
majorGridLines: {
visible: false
},
labels: {
rotation: "auto",
},
plotBands: PlotData
},
tooltip: {
visible: true,
format: "{0}%",
template: "#= series.name #: #= value #"
}
});
}
BindDates();
$(document).ready(function () {
BindDates();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script>
<div id='chart'></div>

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...

Jq tree grid did not load the data from a controller

I am using a jqgrid and i want to display the grid from the jquery a call to controller which return me json data my grid did not show the data code is here
my controller action is like this
private static List<Category> GetProducts(int parent, int childs)
{
string[] procat = { "Electrical", "Computer", "Furniture", "House Hold", "Automobiles" };
var data = new List<Category>();
for (int i = 0; i < parent; i++)
{
data.Add(new Category { CatId = i, CatName = procat[i % 5], Products = new List<Product>() });
for (int j = 0; j < childs; j++)
{
data[i].Products.Add(new Product
{
ProId = j,
ProName = "ABC",
desc = "A web browser built for speed, simplicity, and security",
desc1 = "Google Chrome",
desc2 = (i * j).ToString(),
desc3 = "Copyright 2013 Google Inc. All rights reserved.",
desc4 = i.ToString(),
desc5 = j.ToString(),
desc6 = "Google Chrome",
desc7 = (i * j).ToString(),
desc8 = "Copyright 2013 Google Inc. All rights reserved.",
desc9 = i.ToString(),
desc10 = j.ToString(),
desc11 = "Google Chrome",
desc12 = (i * j).ToString(),
desc13 = "Copyright 2013 Google Inc. All rights reserved.",
desc14 = i.ToString(),
desc15 = j.ToString(),
desc16 = "Google Chrome",
desc17 = (i * j).ToString(),
desc18 = "Copyright 2013 Google Inc. All rights reserved.",
desc19 = i.ToString(),
desc20 = j.ToString(),
desc21 = "Google Chrome",
desc22 = (i * j).ToString(),
desc23 = "Copyright 2013 Google Inc. All rights reserved.",
desc24 = i.ToString(),
desc25 = j.ToString()
});
}
}
return data;
}
public JsonResult PlainObjectsView()
{
var res = new List<FlatProduct>();
string[] procat = { "Electrical", "Computer", "Furniture", "House Hold", "Automobiles" };
int i = 1;
foreach (var item in procat)
{
res.Add(new FlatProduct
{
CatId = i,
CatName = item,
ProName = item,
ProId = i,
level = 0,
parent =null,
Isleaf = false,
IsLoaded = true,
Isexpanded = true
});
i++;
}
var data = GetProducts(5, 5);
foreach (var cats in data)
{
foreach (var prods in cats.Products)
{
res.Add(new FlatProduct
{
CatId = cats.CatId + 1,
CatName = cats.CatName,
ProId = prods.ProId,
ProName = prods.ProName,
desc = prods.desc,
desc1 = prods.desc1,
desc2 = prods.desc2,
desc3 = prods.desc3,
desc4 = prods.desc4,
desc5 = prods.desc5,
desc6 = prods.desc6,
desc7 = prods.desc7,
desc8 = prods.desc8,
desc9 = prods.desc9,
desc10 = prods.desc10,
desc11 = prods.desc11,
desc12 = prods.desc12,
desc13 = prods.desc13,
desc14 = prods.desc14,
desc15 = prods.desc15,
desc16 = prods.desc16,
desc17 = prods.desc17,
desc18 = prods.desc18,
desc19 = prods.desc19,
desc20 = prods.desc20,
desc21 = prods.desc21,
desc22 = prods.desc22,
desc23 = prods.desc23,
desc24 = prods.desc24,
desc25 = prods.desc25,
level = 1,
parent = cats.CatId + 1,
Isleaf = false,
IsLoaded = true,
Isexpanded = true
});
}
}
double pagesize = 5;
var finalRes = new { page = 1, records = res.Count, rows = res, total = Math.Ceiling(res.Count / pagesize), id = res.Select(c=>c.CatId), };
return Json(finalRes, JsonRequestBehavior.AllowGet);
}
and my jquery is like this
<script type="text/javascript">
$(document).ready(function () {
'use strict';
$("#treegrid").jqGrid({
url: '#Url.Content("~/TreeGrid/PlainObjectsView")',
datatype: "json",
mtype: "Get",
colModel: [
{ name: "CatId", width: 150,key:true, hidden:true},
{ name: "CatName", width: 200 },
{ name: "desc", width: 200 },
{ name: "desc1", width: 300 },
{ name: "desc10", width: 300 },
{ name: "desc11", width: 150 },
{ name: "desc12", width: 200 },
{ name: "desc13", width: 300 },
{ name: "desc14", width: 150 },
{ name: "desc15", width: 200 },
{ name: "desc16", width: 300 },
{ name: "desc17", width: 150 },
{ name: "desc18", width: 200 },
{ name: "desc19", width: 300 },
{ name: "desc2", width: 150 },
{ name: "desc20", width: 150 },
{ name: "desc21", width: 200 },
{ name: "desc22", width: 300 },
{ name: "desc23", width: 150 },
{ name: "desc24", width: 200 },
{ name: "desc25", width: 300 },
{ name: "desc3", width: 200 },
{ name: "desc4", width: 300 },
{ name: "desc5", width: 150 },
{ name: "desc6", width: 200 },
{ name: "desc7", width: 300 },
{ name: "desc8", width: 150 },
{ name: "desc9", width: 200 },
{ name: "ProId", width: 300, hidden:true },
{ name: "ProName", width: 150 }
],
treeGridModel: 'adjacency',
height: "auto",
ExpandColumn: 'CatName',
// ExpandColClick: true,
loadonce:true,
treeGrid: true,
// gridview: true,
viewrecords: true,
caption: "Tree Grid Example"
});
});
</script>
help me please where is i m wrong
First of all we should ordered the data in specific json format first add parent and then add its children like this
public IEnumerable<FlatProduct> TreeGridjsonData()
{
var res = PlainObjectsViewNew();
int count = 1;
var list1 = (from rs in res
where rs.parent == null
select rs).ToList<FlatProduct>();
foreach (var item in list1)
{
finalList.Add(
new FlatProduct
{
Id = count,
CatId = item.CatId,
CatName = item.CatName,
level = 0,
parent = null,
Isleaf = false,
//IsLoaded = true,
Isexpanded = false
});
AddChildren(item.CatId, count);
count += 6;
}
return finalList;
}
public IEnumerable<FlatProduct> AddChildren(int parentid, int count)
{
int lscount = count + 1;
var res = PlainObjectsViewNew();
var list1 = from rs in res
where rs.parent == parentid
select rs;
foreach(var item in list1)
{
finalList.Add(new FlatProduct
{
CatName = item.CatName,
ProId = item.ProId,
ProName = item.ProName,
Id = lscount,
desc = item.desc,
desc1 = item.desc1,
desc2 = item.desc2,
desc3 = item.desc3,
desc4 = item.desc4,
desc5 = item.desc5,
desc6 = item.desc6,
desc7 = item.desc7,
desc8 = item.desc8,
desc9 = item.desc9,
desc10 = item.desc10,
desc11 = item.desc11,
desc12 = item.desc12,
desc13 = item.desc13,
desc14 = item.desc14,
desc15 = item.desc15,
desc16 = item.desc16,
desc17 = item.desc17,
desc18 = item.desc18,
desc19 = item.desc19,
desc20 = item.desc20,
desc21 = item.desc21,
desc22 = item.desc22,
desc23 = item.desc23,
desc24 = item.desc24,
desc25 = item.desc25,
level = 1,
parent = count,
Isleaf = true,
IsLoaded = true,
Isexpanded = true
});
lscount++;
}
return finalList;
}
After that convert this list into json format for this
public JsonResult GetPlainobject()
{
var rows = (PlainObjectsViewNew()
.Select(c => new
{
id=c.Id,
cell =new []
{
c.Id.ToString(),
c.CatName,
c.desc,
c.desc1,
c.desc10,
c.desc11,
c.desc12,
c.desc13,
c.desc14,
c.desc15,
c.desc16,
c.desc17,
c.desc18,
c.desc19,
c.desc2,
c.desc20,
c.desc21,
c.desc22,
c.desc23,
c.desc24,
c.desc25,
c.desc3,
c.desc4,
c.desc5,
c.desc6,
c.desc7,
c.desc8,
c.desc9,
c.ProId.ToString(),
c.ProName,
c.level.ToString(),
c.parent.ToString(),
c.Isexpanded.ToString(),
c.IsLoaded.ToString(),
c.Isleaf.ToString(),
}
})).ToArray();
return Json(new
{
page = 1,
records = rows.Length,
rows
}, JsonRequestBehavior.AllowGet);
}
And after that some change in the javascript function
$(document).ready(function () {
$("#treegrid").jqGrid({
url: '#Url.Content("~/TreeGrid/GetPlainobjectOrderdData")',
datatype: "json",
mtype: "Get",
colModel: [
{ name: "CatId", width: 150,key:true, hidden:true},
{ name: "CatName", width: 200 },
{ name: "desc", width: 200 },
{ name: "desc1", width: 300 },
{ name: "desc10", width: 300 },
{ name: "desc11", width: 150 },
{ name: "desc12", width: 200 },
{ name: "desc13", width: 300 },
{ name: "desc14", width: 150 },
{ name: "desc15", width: 200 },
{ name: "desc16", width: 300 },
{ name: "desc17", width: 150 },
{ name: "desc18", width: 200 },
{ name: "desc19", width: 300 },
{ name: "desc2", width: 150 },
{ name: "desc20", width: 150 },
{ name: "desc21", width: 200 },
{ name: "desc22", width: 300 },
{ name: "desc23", width: 150 },
{ name: "desc24", width: 200 },
{ name: "desc25", width: 300 },
{ name: "desc3", width: 200 },
{ name: "desc4", width: 300 },
{ name: "desc5", width: 150 },
{ name: "desc6", width: 200 },
{ name: "desc7", width: 300 },
{ name: "desc8", width: 150 },
{ name: "desc9", width: 200 },
{ name: "ProId", width: 300, hidden:true },
{ name: "ProName", width: 150 }
],
// gridComplete: doGridComplete,
onInitGrid: doOnInitGrid,
loadComplete: doloadComplete,
treeGridModel: 'adjacency',
height: "auto",
ExpandColumn: 'CatName',
//gridview: true,
loadonce:false,
treeGrid: true,
treedatatype:'jsonstring',
viewrecords: true,
treeIcons: { leaf: 'ui-icon-document-b' },
caption: "Tree Grid Example"
});
});
and this is done

Resources