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
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 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>
I am trying to pass some values from jQGrid to controller of my MVC application. The grid was displaying properly but no data was showing.
My code is below
Ajax
function LoadGrid(varLocationID) {
var jqDataUrl = null;
jqDataUrl = "ManageRoutes/ManageRoutes" //+ x;
var Location = varLocationID.getAttribute('value');
var grid = $("#grid").grid({
url: "/ManageRoutes/GetRoutes/",
postData: { "szLocationID": function () { return Location; } },
cache: false,
datatype: "json",
mtype: "POST",
// Specify the column names
colNames: ["RouteID", "CompanyID", "LocationID", "SalesManCode", "SalesManName"],
// Configure the columns
colModel: [
{ name: "RouteID", index: "RouteID", width: 70, align: "left" },
{ name: "CompanyID", index: "CompanyID", width: 200, align: "left" },
{ name: "LocationID", index: "LocationID", width: 200, align: "left" },
{ name: "SalesManCode", index: "SalesManCode", width: 150, align: "left" },
{ name: "SalesManName", index: "SalesManName", width: 170, align: "left" }
],
pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] }
});
and code in controller
[HttpPost]
public JsonResult GetRoutes(string szLocationID)
{
List<RouteNames> qry = new List<RouteNames>();
using (TESTEntities1 dc = new TESTEntities1())
{
qry = (from s in dc.t_hhc_dnl_Route_ID.AsEnumerable()
select new RouteNames
{
CompanyID = s.CompanyID,
LocationID = s.LocationID ,
RouteID = s.RouteID,
SalesManCode=s.SalesManCode ,
SalesManName = s.SalesManName
}).Where(m => m.LocationID.Contains(szLocationID)).Take(100).ToList();
}
var jsonData = new
{
data = from emp in qry select emp
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Any help would be appreciated.
Changed as below code and got worked ..
"ajax": {
"url": "/ManageRoutes/GetRoutes",
"type": "POST",
"data": function (d) {
d.szLocationID = Location;
}
I'm trying to plot a lineal graphic that gets data from ajax using Chartjs 2.5.
This is the main function for this procedure. The main problem is that the legend doesn't appear.
function initDigitalValueChart(divName, ids) {
if ($(divName)) {
/*for (var j=0; j<ids.length; j++) {
console.log(j);
datasetValue[j] = {
fillColor: 'rgba(220,220,220,0.5)',
strokeColor :'rgba(220,220,220,1)',
title :'2013',
data : [Math.round(Math.random() * 1),Math.round(Math.random() * 1)]
}
}*/
var datasetValue = [];
var calls = [];
for (var j = 0; j < ids.length; j++) {
var labels = []
URL = "*****" + ids[j];
calls.push($.getJSON(URL, function(response) {
var values = []
if (response != null) {
$.each(response, function(index, data) {
labels.push(data["timestamp"]);
values.push(data["value"]);
title = data["sensorName"]
});
datasetValue.push({
label: title,
lineTension: 0,
borderColor: "rgba(" + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", 0.70)",
backgroundColor: "transparent",
data: values,
radius: 0,
pointHitRadius: 0,
steppedLine: true,
});
}
}))
}
$.when.apply($, calls).then(function() {
var ctx = document.getElementById('digital').getContext("2d");
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: datasetValue
},
options: {
legend: {
display: true,
labels: {
fontColor: "white",
fontSize: 18
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Data Hora'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Valor'
}
}]
}
}
});
//document.getElementById('digital-legend').innerHTML = lineChart.generateLegend();
});
}
}
I tried to add the position: 'top' option but in this case the console returns
Uncaught TypeError: Cannot read property 'call' of undefined
Has anyone else had problems with this?
I'm trying to 'refresh' or 'reload' a grid and keep the row which has focus after the grid has been reloaded.
I've tried to do it as follows:-
var rowId = $("#dispatch").jqGrid('getGridParam','selrow');
var thisRow = (parseInt(rowId) + parseInt(1));
$("#dispatch").trigger("reloadGrid");
setTimeout(function(){
$("#dispatch").setSelection(thisRow);
}, 151);
But you can see it just from position #1 to the new position.
Is there any other way of reloading the grid and keeping focus position?
Tried:-
// Display Current Jobs
$('#btn-current').bind('click', function() {
$.ajax({
type: 'GET',
url: 'scripts/php/jobs.controller.php',
data: "id=" + "current",
success: function(data){
allButtons.removeClass('active');
$('#btn-current').addClass('active');
$("#dispatch").trigger("reloadGrid", [{current:true}]);
}
});
});
Grid:-
$(function () {
var lastsel2
var rowsToColor = [];
$("#dispatch").jqGrid({
url: 'scripts/xml/jobs.xml',
datatype: "xml",
xmlReader: {
root:"joblist",
row:"job",
repeatitems:false,
},
colNames: ["Time", "Car", "Status", "P", "Pickup", "Zone", "Destination", "Fare", "Name", "Type", "Tel", "Comments", "Account No", "Allow Time", "Tariff", "Email", "Driver Fare", "Driver Extras", "Customer Extras", "Driver", "Driver Comments", "Reference No", "Payment", "From No", "From Street", "From PostCode", "To No", "To Street", "To PostCode", "Account Name", "Flight No", "From Zone No", "To Zone No"],
colModel: [
{ name: "bookingdatetime", width: 55, editable: true },
{ name: "car", width: 45, editable: true },
{ name: "jbmessage", width: 60 },
{ name: "prebooking", width: 10 },
{ name: "pickup", width: 359, editable: true, classes:"grid-col"},
{ name: "zone", width: 50 },
{ name: "dropoff", width: 359, sortable: false, editable: true },
{ name: "customerfare", width: 76, editable: true },
{ name: "passname", width: 100, editable: true },
{ name: "cartype", width: 50, editable: true, },
{ name: "tel", width: 100, editable: true },
{ name: "comments", width: 150 },
{ name: "accountno", hidden: true },
{ name: "allowtime", hidden: true },
{ name: "tarif", hidden: true },
{ name: "emailaddress", hidden: true },
{ name: "driverfare", hidden: true },
{ name: "driverextras", hidden: true },
{ name: "customerextras", hidden: true },
{ name: "driver", hidden: true },
{ name: "comments1", hidden: true },
{ name: "referenceno", hidden: true },
{ name: "payment", hidden: true },
{ name: "fromno", hidden: true },
{ name: "fromstreet", hidden: true },
{ name: "frompostcode", hidden: true },
{ name: "tono", hidden: true },
{ name: "tostreet", hidden: true },
{ name: "topostcode", hidden: true },
{ name: "customer", hidden: true },
{ name: "flightno", hidden: true },
{ name: "fromzoneno", hidden: true },
{ name: "tozoneno", hidden: true }
],
loadComplete: function (){
var rowIds = $('#dispatch').jqGrid('getDataIDs');
for (i = 1; i <= rowIds.length; i++) {//iterate over each row
rowData = $('#dispatch').jqGrid('getRowData', i);
//set background style if Payment = Account
if (rowData['payment'] == 'Acc') {
$('#dispatch').jqGrid('setRowData', i, false, "yellow");
}
if (rowData['payment'] == 'CC') {
$('#dispatch').jqGrid('setRowData', i, false, "purple");
}
if (rowData['cartype'] == 'Est') {
$('#dispatch').jqGrid('setRowData', i, false, "green");
}
if (rowData['cartype'] == '8B' || rowData['cartype'] == 'Bus') {
$('#dispatch').jqGrid('setRowData', i, false, "red");
}
if (rowData['car'] == '00') {
$('#dispatch').jqGrid('setRowData', i, false, "cancel");
}
}
},
pager: "#pager",
loadui: 'disable',
rowNum: 50,
rowList: [10, 20, 30],
sortname: "invid",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
width: null,
shrinkToFit: false,
height: 647,
scrollOffset: 0,
altRows:true,
altclass:'myAltRowClass',
onSelectRow: function (id, status) {
$('#txt-car-number').focus();
$('body').keyup(function (e) {
if (status && e.keyCode == 66 && $("#booking-docket").dialog("isOpen") === false) {
populateDocket();
$("#booking-docket").dialog('open');
}
});
},
gridComplete: function () {
$("#dispatch").setSelection(0, true);
},
});
$("#dispatch").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){
populateDocket();
$("#booking-docket").dialog('open');
}});
$("#dispatch").jqGrid('bindKeys');
function populateDocket() {
var rowId =$("#dispatch").jqGrid('getGridParam','selrow');
var rowData = jQuery("#dispatch").getRowData(rowId);
var bookingdatetime = rowData['bookingdatetime'];
var car = rowData['car'];
var fromno = rowData['fromno'];
var fromstreet = rowData['fromstreet'];
var frompostcode = rowData['frompostcode'];
var tono = rowData['tono'];
var tostreet = rowData['tostreet'];
var topostcode = rowData['topostcode'];
var customerfare = rowData['customerfare'];
var passname = rowData['passname'];
var cartype = rowData['cartype'];
var tel = rowData['tel'];
var comments = rowData['comments'];
var accountno = rowData['accountno'];
var allowtime = rowData['allowtime'];
var tariff = rowData['tarif'];
var email = rowData['emailaddress'];
var driverFare = rowData['driverfare'];
var driverExtras = rowData['driverextras'];
var customerExtras = rowData['customerextras'];
var driver = rowData['driver'];
var commentsdrv = rowData['comments1'];
var referenceno = rowData['referenceno'];
var payment = rowData['payment'];
var accountname = rowData['customer'];
var flightno = rowData['flightno'];
var prebook = rowData['prebooking'];
var bookedby = rowData['bookedby'];
var date = bookingdatetime.split(' ');
var hour = date[1].substr(0,2)
var minute = date[1].substr(6,5)
$('#txt-date').val(date[0]);
$('#txt-hour').val(hour);
$('#txt-min').val(minute);
$('#txt-car').val(car);
$('#txt-pickup-hn').val(fromno);
$('#txt-pickup').val(fromstreet);
$('#txt-destination-hn').val(tono);
$('#txt-destination').val(tostreet);
$('#txt-client-fare').val(customerfare);
$('#txt-passenger').val(passname);
$('#txt-cartype').val(cartype);
$('#txt-telephone').val(tel);
$('#txt-general').val(comments);
$('#txt-account').val(accountno);
$('#txt-lead').val(allowtime);
$('#txt-tariff').val(tariff);
$('#txt-email').val(email);
$('#txt-drv-fare').val(driverFare);
$('#txt-account-name').val(accountname);
$('#txt-driver').val(driver);
$('#txt-office').val(commentsdrv);
$('#p-reference-no').html('-'+referenceno+'-');
$('#txt-payment').val(payment);
$('#txt-flight-no').val(flightno);
$('#txt-prebook').val(prebook);
$('#txt-bookedby').val(bookedby);
}
// Navigate Grids
$(document).keypress(function(e) {
if(e.keyCode == 40) { //down arrow
$('#nextElementId').click();
}
if(e.keyCode == 38) { //up arrow
$('#previousElementId').click();
}
});
$(document).keypress(function(e)
{
if(e.keyCode == 38 || e.keyCode == 40) //up/down arrow override
{
var gridArr = $('#dispatch').getDataIDs();
var selrow = $('#dispatch').getGridParam("selrow");
var curr_index = 0;
for(var i = 0; i < gridArr.length; i++)
{
if(gridArr[i]==selrow)
curr_index = i;
}
if(e.keyCode == 38) //up
{
if((curr_index-1)>=0)
$('#dispatch').resetSelection().setSelection(gridArr[curr_index-1],true);
}
if(e.keyCode == 40) //down
{
if((curr_index+1)<gridArr.length)
$('#dispatch').resetSelection().setSelection(gridArr[curr_index+1],true);
}
}
});
XML DATA:-
<?xml version="1.0"?>
<joblist resultcount="100">
<job id="0">
<pickup>26 CHIPPENHAM MEWS W9 2AN</pickup><dropoff>BREWER STREET W1F 0RJ</dropoff><bookingdatetime>14/05/2014 10:29:19</bookingdatetime><car></car><jbmessage></jbmessage><zone>MOUNTAIN</zone><customerfare>12</customerfare><passname>ele</passname><cartype>Car</cartype><tel>07771764901</tel><comments></comments><accountno></accountno><allowtime>10</allowtime><tarif>1</tarif><emailaddress></emailaddress><driverfare>12</driverfare><driverextras>0</driverextras><customerextras>0</customerextras><driver></driver><comments1></comments1><referenceno>221194</referenceno><payment>Cash</payment><fromno>26</fromno><fromstreet>CHIPPENHAM MEWS</fromstreet><frompostcode>W9 2AN</frompostcode><tono></tono><tostreet>BREWER STREET</tostreet><topostcode>W1F 0RJ</topostcode><prebooking>X</prebooking><customer></customer><flightno></flightno><bookedby>SAJJAD</bookedby><fromzoneno>27</fromzoneno><tozoneno>29</tozoneno></job><job id="1"><pickup>7 FOSBURY MEWS W23JE</pickup><dropoff>HEATHROW TER(T5) TW6 2GA</dropoff><bookingdatetime>13/05/2014 20:57:40</bookingdatetime><car>4</car><jbmessage>PAloc</jbmessage><zone>BALDWIN</zone><customerfare>41</customerfare><passname>BLOECKER</passname><cartype>MPV</cartype><tel>07435358308</tel><comments></comments><accountno></accountno><allowtime>15</allowtime><tarif>2</tarif><emailaddress></emailaddress><driverfare>41</driverfare><driverextras>0</driverextras><customerextras>0</customerextras><driver></driver><comments1></comments1><referenceno>220938</referenceno><payment>Cash</payment><fromno>7</fromno><fromstreet>FOSBURY MEWS</fromstreet><frompostcode>W23JE</frompostcode><tono></tono><tostreet>HEATHROW TER(T5)</tostreet><topostcode>TW6 2GA</topostcode><prebooking>X</prebooking><customer></customer><flightno></flightno><bookedby>SHEERAZ</bookedby><fromzoneno>21</fromzoneno><tozoneno>196</tozoneno>
</job>
</joblist>
Instead of usage setSelection inside of setTimeout you need just use additional parameter of reloadGrid: current:true. See the answer for more details.
UPDATED: The code of gridComplete seems be the reason of your problem:
$("#dispatch").setSelection(0, true);
it resets the selection of the grid after reloading to the row with the id="0".
I would strictly recommend you to replace the code of loadComplete to much more effective rowattr callback. See the answer for the corresponding code example.
Additionally you should not bind $('body').keyup on every row selection. In the way you bind (register) more and more new keyup event handles without unbinding the previous one. I'm not sure what you want to do in the part of the code, but you should probably move the code outside of onSelectRow callback.
I don't see any reason to set ondblClickRow with respect of setGridParam after the grid is created. Instead of that you can just include ondblClickRow callback directly in the list of jqGrid option during creating the grid (like you defined loadComplete, onSelectRow and gridComplete callbacks).
I recommend you to use $(this) instead of $('#dispatch') inside of any jqGrid callback.