jqgrid: unformat is not called while sorting - jqgrid

As per the jqGrid documentation, if you provide a custom formatter in colOptions, you should also provide an 'unformat' key, which gets called during sort operation. However, I don't see this happening ie, the unformat function doesn't get called. Here is an extremely simple example:
As you can see, the console.log line in the unformat_salary function never gets called. Even when you click on the Salary header to sort it. The sort seems to work but it's sorted lexically and I want a custom sort. Providing 'sorttype' as a function would do what I want but I'm wondering why unformat is not getting called when the Documentation specifically says it gets called during sort operations.
JQGRID Test
<script type="text/javascript" src="http://trirand.com/blog/jqgrid/js/jquery.js"></script>
<script type="text/javascript" src="http://trirand.com/blog/jqgrid/js/jquery-ui-1.8.1.custom.min.js"></script>
<script type="text/javascript" src="http://trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="http://trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js"></script>
<style type="text/css" media="screen">
th.ui-th-column div{
white-space:normal !important;
height:auto !important;
padding:2px;
}
</style>
<script type="text/javascript">
$(function() {
createGrid();
});
function createGrid() {
$("#jqgrid-table").jqGrid({
colNames:['First<br/>Name', 'Last Name', 'Age', 'Salary', 'Type'],
colModel:[
{name:'firstName',index:'firstName', width:100},
{name:'lastName',index:'lastName', width:100},
{name:'age', index:'age', width:50},
{name:'salary', index: 'salary', width:50, sortable:true, formatter: salary_formatter, unformat:unformat_salary},
{name:'type', index:'type', width: 56}
],
width: 800,
datatype:'local',
pager: '#pager2',
viewrecords: true,
caption:"JSON Example"
});
var searchOptions = {
caption: 'Filter...',
multipleSearch:true,
closeAfterSearch:true,
closeAfterReset:true,
Find: 'Filter'
};
jQuery("#jqgrid-table").jqGrid('navGrid',
'#pager2',
{search:true, edit:false, add:false, del:false, refresh:false},
null, null, null, searchOptions
);
var data = getData();
for(var i =0; i < data.length; i++) {
var r = data[i];
jQuery("#jqgrid-table").addRowData(r.id, r);
}
}
function getData() {
return [
{id:1, firstName: 'John', lastName: 'XXX', age:'30', salary:'1500', type: 'Nice'},
{id:2, firstName: 'Ashley', lastName:'YYY', age:'31', salary:'1300', type:'Nicer'},
{id:3, firstName:'Smith', lastName:'ZZZ', age:'23', salary:'1301', type:'Nicest'},
{id:4, firstName:'Sarah', lastName:'Aster', age:'45', salary:'530', type:'Nicest'},
{id:5, firstName:'Michelle', lastName:'Crazy', age:'30', salary:'1423', type:'Nicest'}
];
}
function salary_formatter(cellvalue) {
return cellvalue.replace(/^(\d\d)/,'$1,');
}
function unformat_salary(cellvalue) {
console.log('U : ' + cellvalue); // THIS DOES NOT GET CALLED !
return Number(cellvalue.replace(/,/g,''));
}
</script>
</head>
<body>
<div id='jqgrid-div'>
<table id='jqgrid-table'></table>
<div id="pager2"></div>
</div>
</body>
</html>

You misunderstand the meaning of unformat function. It will be soleved only if you get the contain of the cells, rows or columns. For example if you use getCell, getRowData, getCol or close jqGrid methods. If you use datatype:'local' (like in your example) the sorttype property define how the column will be sorted. In case of custom sorting you can use sorttype as function. The function can has two parameters: cellValue and rowData. The last parameter represent the non-formatted data from the current row.
In your case the you can use
sorttype:function(cellvalue){
return unformat_salary(cellvalue);
}

Related

Formatters give incorrect result after sort or search

I have following code using free-jqgrid. It loads correctly for the first time (Status is “Active” and Partner? is “Yes”). But when I do a sort or search, the values become incorrect(Status is “Retired” and Partner? is “No”).
Why the formatters are giving incorrect values? How to fix this?
SCRIPT
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/start/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/js/jquery.jqgrid.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/css/ui.jqgrid.min.css" rel="stylesheet" />
<script type="text/javascript">
function getCurrentPractice ()
{
return "Test";
}
function getGridCaption() {
return "<div style='font-size:15px; font-weight:bold; display:inline; padding-left:10px;'><span class='glyphicon glyphicon-check' style='margin-right:3px;font-size:14px;'></span>" + getCurrentPractice() + " " + "</div>" +
"<div style='float:right; padding-right:20px; padding-bottom:10px; display:inline;>" +
"<div style='float:right;width:550px; padding-bottom:20px;'>" +
"<input type='text' class='form-control' id='filter' placeholder='Search' style='width:250px; height:30px; float:right; ' />" +
" </div>" +
"</div>";
}
$(function () {
var currentPractice = "P";
var grid = $("#list2");
grid.jqGrid({
url: '/Home/GetProviders',
datatype: "json",
postData:
{
practiceName: function () { return currentPractice }
},
colNames: [
'Practice',
'ProviderID',
'Partner?',
'Status'
],
colModel: [
{ name: 'Practice', hidden: false },
{ name: 'ProviderID', hidden: false },
{
name: 'PartnerStatusText',
width: 70,
formatter: function (cellvalue, options, rowObject) {
var isPartner = rowObject.IsPartner;
return isPartner == true ? 'Yes' : 'No';
}
},
{
name: 'ActiveStatusText',
width: 70,
formatter: function (cellvalue, options, rowObject) {
var isActive = rowObject.IsActive;
return isActive == true ? 'Active' : 'Retired';
}
}
],
ignoreCase: true,
loadonce: true,
rowNum: 25,
rowList: [15, 25, 35, 50],
pager: '#pager2',
viewrecords: true,
sortable: true,
caption: getGridCaption(),
beforeSelectRow: function (rowid, e) {
//Avoid selection of row
return false;
},
loadComplete: function () {
}
});
grid.jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false });
//Filter Toolbar
$("#advancedSearch").click(function () {
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
});
//Top Search
$("#filter").on('keyup', function () {
var searchFiler = $("#filter").val(), f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
}
f = { groupOp: "OR", rules: [] };
f.rules.push({ field: "Practice", op: "cn", data: searchFiler });
grid[0].p.search = true;
$.extend(grid[0].p.postData, { filters: JSON.stringify(f) });
grid.trigger("reloadGrid", [{ page: 1, current: true }]);
});
});
</script>
</head>
HTML
<div style="float:left; border:1px solid red;">
<div id="divGrid" style="width: 680px; min-height: 50px; float: left; border: 1px solid silver;">
<table id="list2"></table>
<div id="pager2"></div>
</div>
</div>
Server Code
[AllowAnonymous]
public JsonResult GetProviders(string practiceName)
{
//System.Threading.Thread.Sleep(3000);
List<Provider> providers = new List<Provider>();
Provider p = new Provider();
p.Practice = "Test1";
p.ProviderID = 1;
p.IsActive = true;
p.IsPartner = true;
providers.Add(p);
Provider p2 = new Provider();
p2.Practice = "Test2";
p2.ProviderID = 2;
p2.IsActive = true;
p2.IsPartner = true;
providers.Add(p2);
return Json(providers, JsonRequestBehavior.AllowGet);
}
UPDATE
Thanks to Oleg, working demo can be found here - Fiddle . It uses "/echo/json/" service of JSFiddle to get data from server.
It uses sorttype and additionalProperties. This can be rewritten without additionalProperties - I need to do it when I get a chance to revisit this.
The problem seems be very easy. The data returned from the server contains properties Practice, ProviderID, IsActive and IsPartner. The properties are available in rowObject during initial loading. You use additionally loadonce: true option. Thus free jqGrid will try to save some data locally, but which one? jqGrid saves by default the properties which corresponds the names of columns: Practice, ProviderID, PartnerStatusText and ActiveStatusText, but jqGrid have no information that other properties IsActive and IsPartner need be saved too.
You can solve the problem in two alternative ways:
you rename the column names PartnerStatusText and ActiveStatusText to IsActive and IsPartner.
you add the option additionalProperties: ["IsActive", "IsPartner"] to inform jqGrid to read and save locally additional properties.
Moreover, I'd recommend you to use options.rowData instead of rowObject inside of custom formatter. You can skip the 3-d parameter and to use formatter: function (cellvalue, options) {...}.
The final remark: the current code of the custom formatter is very easy. You need to replace some input values (true and false) to another text. One can use formatter: "select" for the case:
colModel: [
{ name: "Practice" },
{ name: "ProviderID" },
{
name: "IsPartner",
width: 70,
formatter: "select",
formatoptions: { value: "false:No;true:Yes" }
},
{
name: "IsActive",
width: 70,
formatter: "select",
formatoptions: { value: "false:Retired;true:Active" }
}
],
See https://jsfiddle.net/c9fge9yk/1/

How to disable the cell if the date is empty or null or undefined?

I'm new to jqgrid and jquery, can someone please help me in disabling the cell when the date is null or empty or undefined?
Actually the json for some (rows,col) date data is there and for some it is not there.
I want to disable the cell in the row for which Date data is not available.
grid cell editing POC
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="/jqGrid/jquery-ui-1.11.4.custom/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/jqGrid/Guriddo_jqGrid_JS_5.0.1/css/ui.jqgrid.css">
<script type="text/ecmascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/jqGrid/jquery-ui-1.11.4.custom/jquery-ui.min.js"></script>
<script type="text/javascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript">
$.jgrid.useJSON = true;
</script>
<script type="text/javascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/src/jquery.jqGrid.js"></script>
<script type="text/javascript">
$(function () {
"use strict";
var grid = $("#tree");
var initDateWithButton = function (elem) {
var ids = grid.jqGrid('getDataIDs');
for (var i=0;i<ids.length;i++) {
var id=ids[i];
if (grid.jqGrid('getCell',id,'assignedDate') == null) {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
if (grid.jqGrid('getCell',id,'assignedDate') == "") {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
if (grid.jqGrid('getCell',id,'assignedDate') == undefined) {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
}
if (/^\d+%$/.test(elem.style.width)) {
// remove % from the searching toolbar
elem.style.width = '';
}
// to be able to use 'showOn' option of datepicker in advance searching dialog
// or in the editing we have to use setTimeout
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
showWeek: false,
showButtonPanel: true,
buttonImage: 'http://rcban0015:10039/GridPOC/pages/calenderIcon.gif',
onClose: function (dateText, inst) {
inst.input.focus();
}
});
$(elem).next('button.ui-datepicker-trigger').button({
text: false,
position: "relative",
top: "4px"
});
}, 100);
},
dateTemplate = {align: 'center', sorttype: 'date', editable: true,
formatter: 'date', formatoptions: { newformat: 'd-M-Y' }, datefmt: 'd-M-Y',
editoptions: { dataInit: initDateWithButton, size: 11 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton,
size: 11, // for the advanced searching dialog
attr: {size: 11} // for the searching toolbar
}},
lastSel;
jQuery('#tree').jqGrid({
url: '<%= webAppAccess.getBackchannelActionURL("actionListjqGridPagination",false) %>',
"colModel":[
{
"name":"course_id",
"index":"course_id",
"sorttype":"int",
"key":true,
"hidden":true,
"width":50
},{
"name":"courseName",
"index":"courseName",
"sorttype":"string",
"label":"courseName",
"width":200
},{
"name":"facility",
"index":"facility",
"label":"facility",
"width":200,
"align":"left"
},{
"name":"assignedDate",
"index":"assignedDate",
"label":"assignedDate",
"width":110,
"template": dateTemplate
},{
"name":"dueDate",
"index":"dueDate",
"label":"dueDate",
"width":110,
"template": dateTemplate
},
{
"name":"AssignmentStatus",
"index":"AssignmentStatus",
"label":"AssignmentStatus",
"width":50
},{
"name":"Action",
"index":"Action",
"label":"Action",
"width":50
},
{
"name":"lft",
"hidden":true
},{
"name":"rgt",
"hidden":true
},{
"name":"level",
"hidden":true
},{
"name":"uiicon",
"hidden":true
}
],
"jsonReader": { "repeatitems": false, "root": "employees.rows" },
"toolbar": [true, "top"],
"width":"1200",
"hoverrows":false,
"viewrecords":false,
"gridview":true,
"height":"auto",
"sortname":"lft",
"loadonce":true,
"rowNum": 2,
"rowList":[2,10,15],
"scrollrows":true,
// enable tree grid
"treeGrid":true,
// which column is expandable
"ExpandColumn":"courseName",
// datatype
"treedatatype":"json",
// the model used
"treeGridModel":"nested",
// configuration of the data comming from server
"treeReader":{
"left_field":"lft",
"right_field":"rgt",
"level_field":"level",
"leaf_field":"isLeaf",
"expanded_field":"expanded",
"loaded":"loaded",
// set the ui icon field froom data
"icon_field":"uiicon"
},
"sortorder":"asc",
"datatype":"json",
"pager":"#pager",
"cellEdit": true, // TRUE = turns on celledit for the grid.
"cellsubmit" : 'clientArray',
"editurl": 'clientArray'
});
$('#t_' +"tree")
.append($("<div><label for=\"globalSearchText\">Global search in grid for: </label><input id=\"globalSearchText\" type=\"text\"></input> <button id=\"globalSearch\" type=\"button\">Search</button></div>"));
$("#globalSearchText").keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
if (key === $.ui.keyCode.ENTER) { // 13
$("#globalSearch").click();
}
});
$("#globalSearch").button({
icons: { primary: "ui-icon-search" },
text: false
}).click(function () {
var postData = jQuery('#tree').jqGrid("getGridParam", "postData"),
colModel = jQuery('#tree').jqGrid("getGridParam", "colModel"),
rules = [],
searchText = $("#globalSearchText").val(),
l = colModel.length,
i,
cm;
for (i = 0; i < l; i++) {
cm = colModel[i];
if (cm.search !== false && (cm.stype === undefined || cm.stype === "text")) {
rules.push({
field: cm.name,
op: "cn",
data: searchText
});
}
}
postData.filters = JSON.stringify({
groupOp: "OR",
rules: rules
});
jQuery('#tree').jqGrid("setGridParam", { search: true });
jQuery('#tree').trigger("reloadGrid", [{page: 1, current: true}]);
return false;
});
});
</script>
</head>
<body>
<table id="tree"><tr><td></td></tr></table>
<div id="pager"></div>
</body>
</html>
There are exist alternative fork of jqGrid: free jqGrid, which I develop since more as one year. It has the functionality, where one can define editable property of colModel as function, which can return true or false based on the cell or the row content. See the wiki article for more details.
Check if this How to disable editing for soe cells in row editing of JQGrid
helps, it seen it is a similar thing, You just need to add into your logic.

JQGrid is not working in ASP.net mvc 4?

This is controller code:
using JQGird.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JQGird.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public JsonResult EmployeeDetail()
{
Database1Entities db = new Database1Entities();
var employeedata = db.Empployees.Select(data => new
{
data.Id,
data.Name,
data.Designation,
data.Address,
data.Salary
});
var jsondat = new
{
total = 1,
page = 1,
records = db.Empployees.ToList().Count,
rows = employeedata
};
return Json(jsondat, JsonRequestBehavior.AllowGet);
}
}
}
and this is view of index action method
#{
ViewBag.Title = "Index";
}
<header>
<script>
$(document).ready(function () {
$('#grid').jqGrid({
url: '/Home/EmployeeDetails',
datatype: 'json',
myType: 'GET',
colNames: ['Id', 'Name', 'Designation', 'Address', 'Salary'],
colModel: [
{ name: 'Id', index: 'Id' },
{ name: 'Name', index: 'Name' },
{ name: 'Designation', index: 'Designation' },
{ name: 'Address', index: 'Address' },
{ name: 'Salary', index: 'Salary' }
],
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
reocords: 'records',
id: '0',
repeatitems: false
},
pager: $('#pager'),
rowNum: 5,
rowList: [2, 5, 10],
width: 600,
viewrecords: true,
caption: 'Jqgrid MVC Tutorial'
});
});
</script>
<script src="~/Scripts/jquery.jqGrid.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
</header>
<h1>Records of employees</h1>
<div>
<table id="grid">
</table>
<div id="pager"></div>
</div>
When i run the application, i t only show data. I have also check that the Json data is coming successffully to the view but jqgrid is not working. What mistakes i am doing?
HTML of the page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.5.3.js"></script>
</head>
<body>
<h1>Records of employees</h1>
<div>
<table id="grid">
</table>
<div id="pager"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#grid').jqGrid({
url: '/Home/EmployeeDetail',
datatype: 'json',
//myType: 'GET',
loadonce: true,
colNames: ['Id', 'Name', 'Designation', 'Address', 'Salary'],
colModel: [
{ name: 'Id', index: 'Id' },
{ name: 'Name', index: 'Name' },
{ name: 'Designation', index: 'Designation' },
{ name: 'Address', index: 'Address' },
{ name: 'Salary', index: 'Salary' }
],
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
reocords: 'records',
id: '0',
repeatitems: false
},
pager: $('#pager'),
rowNum: 5,
rowList: [2, 5, 10],
width: 600,
viewrecords: true,
caption: 'Jqgrid MVC Tutorial'
});
});
</script>
<link href="/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="/Scripts/jquery-1.9.1.min.js"></script>
<script src="/Scripts/i18n/grid.locale-en.js"></script>
<script src="/Scripts/jquery.jqGrid.min.js"></script>
<script src="/Scripts/jquery.jqGrid.js"></script>
</body>
</html>
The HTML page have wrong order of JavaScripts which you includes.
It's important to understand that jqGrid is jQuery plugin. So one have to include first jQuery and only then one can includes jqGrid JavaScript files.
In the same way you use $(document).ready(function () {...}); which contains $ and .ready defined by jQuery, but you use the code before you included jQuery file jquery-1.9.1.min.js.
The next error: you included both non-minimized jqGrid jquery.jqGrid.js and then minimized version of the same file jquery.jqGrid.min.js. It's wrong. You should include only one from the files.
One more problem could exist in the order of the main jqGrid file (jquery.jqGrid.min.js, jquery.jqGrid.js or jquery.jqGrid.src.js) and the corresponding locale file grid.locale-en.js. There are different requirements for different versions of jqGrid and different forks, but the recommended order which works in all versions of jqGrid is: first include locale file (like grid.locale-en.js) and then the main jqGrid file (like jquery.jqGrid.min.js).
you skipped <body>...</body> after </header>.
The code of EmployeeDetail action don't uses any parameters which jqGrid send. You don't implemented any paging and sorting in the server code. Instead of that you just return all data at once. You should use loadonce: true options in the case. jqGrid will load all the data and then it will use sorting, paging and filtering on the client side. I hope that you use jqGrid in version higher as 3.7 which implemented support of loadonce: true. If you use loadonce: true option then the total, page and records properties of the server response will be ignored. Thus you can reduce the code of the server side and use return Json(employeedata, JsonRequestBehavior.AllowGet); instead of return Json(jsondat, JsonRequestBehavior.AllowGet);.
There are no myType option, but there are exist mtype option which default value is 'GET'. So you should remove myType: 'GET' option which will be ignored by jqGrid.
Some options of jqGrid can depend from the version of jqGrid which you use. I would recommend you to use gridview: true, autoencode: true, height: "auto". I would recommend you to remove unneeded index properties from all columns defined in colModel. Instead of that you can add key: true option for Id column. It will inform jqGrid to use the values from the columns as the values of id attribute of the rows (id of <td> elements). The jsonReader can be removed or you can use jsonReader: { repeatitems: false } or jsonReader: { repeatitems: false, root: function (obj) { return obj; } }. If you use recent version of jqGrid then no jsonReader will be required.
I mentioned above multiple times about versions which you use. I would recommend you to update jQuery 1.9.1 which you use currently to jQuery 1.11.3 or 2.1.4. Moreover I would recommend you to use the latest version of free jqGrid which you can get either from NuGet (see here), used URLs from CDN (see the wiki article) or to download the latest sources from GitHub directly.

data-bind not working in List View template within Grid detail template

I need help using a Kendo UI list view which lives within a grid row detail template.
here is something I have done so far.
<div id="grid">
</div>
<script type="text/x-kendo-template" id="gridDetailTemplate">
<div class='grid-edit'>
<div class='edit-list'></div>
</div>
</script>
<script type="text/x-kendo-template" id="editItemtemplate">
<div class='edit-Item'>
#if(Type=='string'){#
<ul><li><b>#:Name#</b></li><li><input class='inputString' value='#:DataVal()#'/></li></ul>
#}else if(Type=='number'){#
<ul><li><b>#:Name#</b></li><li><input class='inputNumber' data-role='numerictextbox' data-type='number' value='#:DataVal()#'/></li></ul>
#}else if(Type=='date'){#
<ul><li><b>#:Name#</b></li><li><input class='inputDate' data-role='datepicker' value='#:kendo.toString(DataVal(),'MM/dd/yyyy')#'/></li></ul>
#}else if(Type=='boolean'){Name #<input type='checkbox'/>
#}#
</div>
</script>
<script type="text/javascript">
$(document).ready(function () {
$.get("http://localhost:4916/DataAttribute", function (data, status) {
var selFields = new Object();
$.each(data, function (index, elem) {
selFields[elem.Name] = new Object();
selFields[elem.Name]["type"] = elem.Type;
});
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: { url: "http://localhost:4916/Deal",
dataType: "json"
}
},
schema: {
data: "Data", total: "Total",
model: {
fields: selFields
}
}
},
height: 430,
filterable: true,
sortable: true,
pageable: false,
detailTemplate: kendo.template($("#gridDetailTemplate").html()),
detailInit: detailInit,
columns: [{
field: "SecurityName",
title: "Security Name",
width: 250
},
{
field: "DateOfAcquisition",
title: "Date Of Acquisition",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "Acres",
title: "Acres",
width: 120
}
]
});
});
});
function detailInit(e) {
$.get("http://localhost:4916/DataAttribute", function (data, status) {
var detailRow = e.detailRow;
detailRow.find(".edit-list").kendoListView({
dataSource: {
data: data,
schema: {
model: {
DataVal: function () {
switch (this.get("Type")) {
case "number"
}
if (e.data[this.get("Name")])
return e.data[this.get("Name")];
else
return '';
}
}
}
},
template: kendo.template($("#editItemtemplate").html())
});
});
}
</script>
My code gets dynamic field list and binds it to the data source for grid.
Then, in the detailInit event, I find the div within row detail and convert it into kendo UI list, for which the template have been created.
Now, when I use data-bind="value: DataVal()" ,it doesn't pick up the values of List data source. It works the way I have done i.e. value="#: DataVal() #". But, data-role does not convert the fields to specified types which are datepicker and numericinput in my case.
I believe that data-role not being used is caused due to same issue as data-bind not being read.
Can anyone help me out with this? Also, feel free to suggest any alternate ways and general code improvements. I am an ASP.NET developer and usually don't work on pure html and javascript.
PS: I would be happy to provide the context on what I am trying to achieve here if anyone is interested.
Thanks in advance.
If you can rig up a jsFiddle or jsBin example that would help debug the issue.
However, try removing the parenthesis:
data-bind="value: DataVal"
Kendo should detect that DataVal is a function and call it on its own.
I experienced a similar situation in a listview template. I created a JSFiddle to demonstrate:
http://jsfiddle.net/zacharydl/7L3SL/
Oddly, the solution is to wrap the contents of the template in a div. It looks like your template already has this, so YMMV.
<div id="example">
<div data-role="listview" data-template="template" data-bind="source: array"></div>
</div>
<script type="text/x-kendo-template" id="template">
<!--<div>-->
<div>method 1: #:field#</div>
<div>method 2: <span data-bind="text: field"></span></div>
<input data-role="datepicker" />
<!--</div>-->
</script>
var model = kendo.observable({
array: [
{ field: 'A'},
{ field: 'B'}
]
});
kendo.bind($('#example'), model);

jqgrid search popup allows all filters to be removed!

I'm trying out very simple search popup on the JqGrid. Please see the code below. There are few issues:
The popup comes up with AND/OR and [+] controls at the very top. See screenshot below: (from FF 4)
You can click on [-] button to remove the very first (and only) filter row. It shouldn't be allowed. First filter row should never be allowed to be removed.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>JQGRID Test</title>
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/redmond/jquery-ui-1.8.1.custom.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/ui.jqgrid.css"/>
<script type="text/javascript" src="http://trirand.com/blog/jqgrid/js/jquery.js"></script>
<script type="text/javascript" src="http://trirand.com/blog/jqgrid/js/jquery-ui-1.8.1.custom.min.js"></script>
<script type="text/javascript" src="http://trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="http://trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript">
$(function() {
createGrid();
});
function createGrid() {
$("#jqgrid-table").jqGrid({
colNames:['First Name', 'Last Name', 'Age', 'IQ', 'Type'],
colModel:[
{name:'firstName',index:'firstName', width:100},
{name:'lastName',index:'lastName', width:100},
{name:'age', index:'age', width:50},
{name:'iq', index:'iq', width:50, stype:'select', searchoptions: {dataUrl:'/api/domains/putcalldomain'}},
{name:'type', index:'type', width: 56}
],
width: 800,
datatype:'local',
pager: '#pager2',
viewrecords: true,
caption:"JSON Example"
});
var searchOptions = {
caption: 'Filter...',
multipleSearch:true,
closeAfterSearch:true,
closeAfterReset:true,
Find: 'Filter'
};
jQuery("#jqgrid-table").jqGrid('navGrid',
'#pager2',
{search:true, edit:false, add:false, del:false, refresh:false},
null, null, null, searchOptions
);
var data = getData();
for(var i =0; i < data.length; i++) {
var r = data[i];
jQuery("#jqgrid-table").addRowData(r.id, r);
}
}
function getData() {
return [
{id:1, firstName: 'John', lastName: 'XXX', age:'30', iq:'200', type: 'Nice'},
{id:2, firstName: 'Ashley', lastName:'YYY', age:'31', iq:'210', type:'Nicer'},
{id:3, firstName:'Smith', lastName:'ZZZ', age:'23', iq:'90', type:'Nicest'}
];
}
</script>
</head>
<body>
<div id='jqgrid-div'>
<table id='jqgrid-table'></table>
<div id="pager2"></div>
</div>
</body>
</html>
I suggest to overwrite the internal reDraw method used by filtering (see my another answer for more description). To do this you should include in the searchOptions which you use the beforeShowSearch event handler with the following implementation:
beforeShowSearch: function($form) {
var searchDialog = $form[0],
oldrReDraw = searchDialog.reDraw, // save the original reDraw method
doWhatWeNeed = function() {
$('input.delete-rule:first',searchDialog).unbind('click');
// set fucus in the last input field
setTimeout(function() {
// set fucus in the last input field
$('input[type="text"]:last',searchDialog).focus();
}, 50);
}
searchDialog.reDraw = function() {
oldrReDraw.call(searchDialog); // call the original reDraw method
doWhatWeNeed();
}
doWhatWeNeed();
}
You can see the corresponding demo here.

Resources