need help with sorting these json results by days inside kendoGrid. I need a way to turn the plus sign into .5 or something along those lines. I suppose I have to loop through each one, if i find the plus sign then change the value to number.5 and then drop the new value back in before displaying?
{ name: Alex, days: "2" },
{ name: Jason, days: "1" },
{ name: Fred, days: "2+" },
{ name: Jane, days: "3" },
{ name: John, days: "3+" }
Here is code I got working
<body>
<div id="grid">
</div>
<div>
<script>
$(document).ready(function () {
//JSON data
var people = [
{ firstName: "Hasibul", lastName: "Haque", email: "hasibul2363#gmail.com", rank:"2" }
, { firstName: "Jane", lastName: "Smith", email: "jane.smith#kendoui.com", rank: "3+" }
, { firstName: "Jason", lastName: "Doe", email: "hasibul2363#gmail.com", rank: "1" }
, { firstName: "John", lastName: "doe", email: "hasibul2363#gmail.com", rank: "3+" }
, { firstName: "Joan", lastName: "doe", email: "hasibul2363#gmail.com", rank: "5" }
, { firstName: "Jack", lastName: "doe", email: "hasibul2363#gmail.com", rank: "3" }
, { firstName: "Jacob", lastName: "doe", email: "hasibul2363#gmail.com", rank: "3-" }
, { firstName: "Joe", lastName: "doe", email: "hasibul2363#gmail.com", rank: "3-" }
];
$('#grid').kendoGrid({
dataSource: {
type: "json",
data: people,
pageSize: 15,
sort: ({ field: "rank" })
},
sortable: true,
columns:[{
field: "rank",
sortable: {
compare: function (a, b, asc) {
var s1 = a.rank;
var s2 = b.rank;
var n1, n2;
var sg1, sg2;
var plus = s1.indexOf('+');
var minus = s1.indexOf('-');
if(plus >= 0){
n1 = parseInt(s1.substr(0, plus));
sg1 = 1;
}
else if(minus >= 0){
n1 = parseInt(s1.substr(0, minus));
sg1 = -1;
}
else{
n1 = parseInt(s1);
sg1 = 0;
}
plus = s2.indexOf('+');
minus = s2.indexOf('-');
if (plus >= 0) {
n2 = parseInt(s2.substr(0, plus));
sg2 = 1;
}
else if (minus >= 0) {
n2 = parseInt(s2.substr(0, minus));
sg2 = -1;
}
else {
n2 = parseInt(s2);
sg2 = 0;
}
if (n1 == n2) {
return sg2 - sg1;
} else {
return n2 - n1;
}
}
}
}]
,
pageable: {
buttonCount: 1
},
schema: {
data: "people"
}
//binding JSON data with grid
});
});
</script>
Related
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.
I am using Nested-datatables (https://github.com/AndrejGajdos/nested-datatables) so I have to use JSON.
I want to pass JSON from the controller to ajax and then use it in order to create a nested table.
The problem is that I need the exact JSON format so I will not get "undefined" result.
This is the example of the JSON format that I need (like in the link above) :
var dataInJson = [
{
data: {
name: 'b1',
street: 's1',
city: 'c1',
departments: 10,
offices: 15
},
kids: [
{
data: {
department: 'HR',
supervisor: 'Isidor Bristol',
floor: 1,
employees: 15
},
kids: [
{
data: {
name: 'Klement Nikodemos',
phone: '+938462',
hire_date: 'January 1, 2010',
id: 3456
},
kids: []
},
{
data: {
name: 'Madhava Helmuth',
phone: '+348902',
hire_date: 'May 23, 2002',
id: 1234
},
kids: []
},
{
data: {
name: 'Andria Jesse',
phone: '456123',
hire_date: 'October 23, 2011',
id: 9821
},
kids: []
}
]
},
{
data: {
department: 'development',
supervisor: 'Jim Linwood',
floor: 2,
employees: 18
},
kids: [
{
data: {
name: 'Origenes Maxwell',
phone: '345892',
hire_date: 'February 1, 2004',
id: 6234
},
kids: []
}
]
},
{
data: {
department: 'testing',
supervisor: 'Zekeriya Seok',
floor: 4,
employees: 11
},
kids: []
}
]
},
{
data: {
name: 'b2',
street: 's10',
city: 'c2',
departments: 3,
offices: 10
},
kids: [
{
data: {
department: 'development',
supervisor: 'Gallagher Howie',
floor: 8,
employees: 24
},
kids: [
{
data: {
name: 'Wat Dakota'
},
kids: []
}
]
},
{
data: {
department: 'testing',
supervisor: 'Shirley Gayle',
floor: 4,
employees: 11
},
kids: []
}
]
},
{
data: {
name: 'b3',
street: 's3',
city: 'c3',
departments: 2,
offices: 1
},
kids: [
{
data: {
department: 'development'
},
kids: [
{
data: {
name: 'Wat Dakota'
},
kids: []
}
]
},
{}
]
},
{
data: {
name: 'b4',
city: 'c4'
},
kids: []
}
];
In controller I have ajax function:
public function ajax(){
$parent = FirstLine::
select('yehida','data_type')
->where('first_year',2019)->where('second_year',2019)->where('first_period_no',1)->where('second_period_no',2)->where('periodical','רבעוני')
->addSelect(DB::raw('SUM(first_period) as first_period'))
->groupBy('yehida')
->groupBy('data_type')
->orderBy('yehida')
->orderBy('data_type')
->get();
$child = FirstLine::
select('yehida','hativa','data_type')
->where('first_year',2019)->where('second_year',2019)->where('first_period_no',1)->where('second_period_no',2)->where('periodical','רבעוני')
->addSelect(DB::raw('SUM(first_period) as first_period'))
->groupBy('yehida')
->groupBy('hativa')
->groupBy('data_type')
->orderBy('yehida')
->orderBy('hativa')
->orderBy('data_type')
->get();
$value = [];
foreach ($parent as $ch) {
$options = [];
foreach($child as $ch2) {
$options[] = ['data' => [
'yehida' => $ch2->yehida,
'hativa' => $ch2->hativa,
'data_type' => $ch2->data_type,
'first_period' => $ch2->first_period],
'kids' => []
];
if($ch->yehida == $ch2->yehida){
$value[] = [
'data' =>[
'yehida' => $ch->yehida,
'data_type' => $ch->data_type,
'first_period' => $ch->first_period
],
'kids' =>
$options,
];
}
}
}
$value = json_encode($value);
return response()->json($value);
}
My script with ajax call:
<script>
var temp;
$.ajax({
'async': false,
type: 'GET', //THIS NEEDS TO BE GET
url: '{!! route('get.ajax') !!}',
dataType: 'json',
success: function (data) {
temp = data;
},error:function(){
console.log(data);
}
});
var dataInJson = temp;
var settings = {
iDisplayLength: 20,
bLengthChange: false,
bFilter: false,
bSort: false,
bInfo: false
};
var tableT = new nestedTables.TableHierarchy(
'example',
dataInJson,
settings
);
tableT.initializeTableHierarchy();
var tableEle = document.querySelector('#example .table');
tableEle.addEventListener('onShowChildHierarchy', function(e) {
console.log(e);
});
// '#example' is wrapper ID for table hierarchy
var tableEle = document.querySelector('#example .table');
tableEle.addEventListener('onHideChildHierarchy', function(e) {
console.log(e);
});
</script>
How am I supposed to build my own JSON format so it will be like the JSON example? please help me
I have data coming from the server like
Id AppId
1 23
2 28
1 69
1 123
What is the way to make it like this on kendo grid
Id AppId
1 23,69,123
2 28
You can use the group feature of the datasource:
var data = [
{Id: 1, AppId: 23},
{Id: 2, AppId: 28},
{Id: 1, AppId: 69},
{Id: 1, AppId: 123},
];
var ds = new kendo.data.DataSource({
data: data,
schema: {
model: {
fields: {
Id: { type: "number" },
AppId: { type: "number" },
}
}
},
group: {
field: "Id"
}
});
Then if you want to use the grid group by feature:
$("#grid").kendoGrid({
dataSource: ds,
columns: [
{ field: "Id", title: "ID", },
{ field: "AppId", title: "Application ID" },
]
});
If you want the comma delimited list, use the fetch() method of the datasource to build the new data array:
var groupedData = [];
ds.fetch(function(){
var data = this.view();
for (var i=0; i< data.length; i++){
var id = data[i].value;
var text = '';
for (var j=0; j< data[i].items.length; j++){
text += data[i].items[j].AppId;
if (j< data[i].items.length - 1){
text += ',';
}
}
groupedData.push({Id: id, AppId: text});
}
});
$("#grid2").kendoGrid({
dataSource: groupedData,
columns: [
{ field: "Id", title: "ID", },
{ field: "AppId", title: "Application ID" },
]
});
The following DOJO presents both options:
DEMO
I am working on Kendo date time picker.I am getting a problem when clicking the submit button.
1)Having To date and From date pickers .how to get the popup that should validate both the date and time and it should not allows the alphabets.
$("#startdatetimepicker").kendoDateTimePicker({
showSecond: true,
dateFormat: "dd-mm-yy",
timeFormat: "HH:mm:ss",
format: "dd-MM-yy HH:mm:ss",
mindate: getFormattedDate(new Date())
}).data("kendoDateTimePicker");
$("#startdatetimepic").attr("readonly", "readonly");
function getFormattedDate(date) {
alert("")
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear().toString().slice(2);
return day + '-' + month + '-' + year;
}
$("#enddatetimepicker").kendoDateTimePicker({
showSecond: true,
dateFormat: "dd-mm-yy",
timeFormat: "HH:mm:ss",
format: "dd-MM-yy HH:mm:ss"
}).data("kendoDateTimePicker");
var result = $("#grid").kendoGrid({
filterable: true,
columns: [{
field: "FirstName",
title: "First Name"
}, {
field: "LastName",
title: "Last Name"
}, {
field: "dob",
title: "DOB",
format: "{0:dd-MM-yy HH:mm:ss}"
}],
dataSource: {
data: [ {
FirstName: "Joe",
LastName: "Smith",
dob: "2013-02-01 19:54:13"
}, {
FirstName: "Jane",
LastName: "Smith",
dob: "2013-02-02 20:55:14"
}, {
FirstName: "Jane",
LastName: "Smith",
dob: "2013-02-03 21:56:15"
},
{
FirstName: "Jane",
LastName: "Smith",
dob: "2013-03-4 20:56:14"
}],
schema: {
data: function (data) {
$.each(data, function (i, val) {
val.dob = kendo.parseDate(val.dob, "yyyy-MM-dd HH:mm:ss");
});
return data;
}
}
}
}).data("kendoGrid");
$("#filter").on("click", function () {
var mindate = $('#startdatetimepicker').data("kendoDateTimePicker").value();
var maxdate = $('#enddatetimepicker').data("kendoDateTimePicker").value();
var condition = {
logic: "and",
filters: []
};
if (mindate !== null) {
condition.filters.push({
field: "dob",
operator: "ge",
value: mindate
});
}
if (maxdate !== null) {
condition.filters.push({
field: "dob",
operator: "le",
value: maxdate
});
}
result.dataSource.filter(condition);
});
here is the fiddle:http://jsfiddle.net/5bchz/97/
The format should prohibit alpha characters while incrementing the values can be achieved similar to:
function incrementDay(increment) {
var datePicker = $("#DayPager").data("kendoDatePicker");
var val = datePicker.value();
var newDate = new Date(val.getFullYear(), val.getMonth(), val.getDate() + increment);
datePicker.value(newDate);
}
My json call returns an object array:
[
{
Table: 1,
FirstName: "Bert",
LastName: "Smith",
Place: 1
},
{
Table: 1,
FirstName: "Suzanne",
LastName: "Smith",
Place: 2
},
{
Table: 1,
FirstName: "Matthew",
LastName: "Stewart",
Place: 3
},
{
Table: 1,
FirstName: "Brian",
LastName: "Robinson",
Place: 4
},
{
Table: 1,
FirstName: "Jennifer",
LastName: "Robinson",
Place: 5
},
{
Table: 1,
FirstName: "Andrew",
LastName: "Caygill",
Place: 6
},
{
Table: 1,
FirstName: "Susan",
LastName: "Caygill",
Place: 7
},
{
Table: 1,
FirstName: "John",
LastName: "Spreadbury",
Place: 8
},
{
Table: 1,
FirstName: "Anne-Marie",
LastName: "Nevin",
Place: 9
}]
I have a template in my HTML:
<script type="text/html" id="dataLine">
<div class="itemLine">
<div class="Name">
<span class="fixtureBoxLine" data-bind="text: fullName"></span>
</div>
<div class="TableNo">
<span class="fixtureBoxLine" data-bind="text: Table"></span>
</div>
</div>
</script>
and the binding is:
<div data-bind="template: { name: 'dataLine', foreach: pageCol1 }"></div>
My viewmodel is:
var viewModel = {
fields: ko.observableArray([]),
pageSize: ko.observable(1),
pageIndex: ko.observable(0)
};
viewModel.pageCol1 = ko.computed(function() {
var size = Number(this.pageSize());
var start = this.pageIndex() * size * 2; //2 cols per page
var end = start + size;
return this.fields.slice(start, end);
}, viewModel);
All works fine except I can't get a "fullname" property. If I try adding it to the viewmodel in the same way as I did with "pageCol1" above, then as my json success property just does:
viewModel.fields(xlData);
it doesn't work as there is no "fullName" property on the data returned.
I feel I've tried every possible combination today and have now given myself a headache! Please would someone point me in the right direction?
Thanks!
Try extending your pageCol1 by adding new field (concatenated from another two) to your response array like:
viewModel.pageCol1 = ko.computed(function() {
var size = Number(this.pageSize());
var start = this.pageIndex() * size * 2; //2 cols per page
var end = start + size;
for( var i = 0, len = this.fields.length; i < len; i++ ) {
this.fields[ i ].fullName = this.fields[ i ].FirstName + ' ' + this.fields[ i ].LastName;
}
return this.fields.slice(start, end);
}, viewModel);
so in final result before you're iterating over your array it will be like:
[
{
Table: 1,
FirstName: "Bert",
LastName: "Smith",
fullName: "Bert Smith",
Place: 1
},
{
Table: 1,
FirstName: "Suzanne",
LastName: "Smith",
fullName: "Suzanne Smith",
Place: 2
},
{
Table: 1,
FirstName: "Matthew",
LastName: "Stewart",
fullName: "Matthew Stewart",
Place: 3
},
...