Data doesn't refresh on clicking on next button on Jqgrid - jqgrid

<script language="javascript" type="text/javascript" src="/SiteAssets/test%20js/jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/JqLib/i18n/grid.locale-en.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/JqLib/jquery.jqGrid.min.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/JqLib/jquery.SPServices-0.7.2.min.js"></script>
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/json2/20150503/json2.min.js"></script>
<link rel="stylesheet" href="/SiteAssets/styles/ui.jqgrid.css">
<link rel="stylesheet" href="/SiteAssets/styles/ui-lightness/jquery-ui-1.7.3.custom.css">
<script language="javascript" type="text/javascript">
$(document).ready(function() {
debugger;
jQuery("#list").jqGrid({
datatype: GetMyData,
colNames:["ID","Title","Description"],
colModel:[{name:'ID',index:'ID',align:'left',sortable: true,width:"1500px"},
{name:'Title',index:'Title',align:'left',sortable: true, width:"1500px"},
{name:'Description',index:'Description',align:'left',sortable:true, width:"1500px"},],
pager: true,
pager: '#pager',
pageinput: true,
rowNum: 5,
rowList: [5, 10, 20, 50, 100],
sortname: 'ID',
sortorder: "asc",
viewrecords: true,
autowidth: true,
emptyrecords: "No records to view",
loadonce: true,
loadtext: "Loading..."
});
jQuery("#list").jqGrid('navGrid', "#pager", { edit: false, add: false, del: false, search: true, refresh: true }); });
function GetMyData(){
var ex='e';
Query="<Query><Where><Or><Contains><FieldRef Name='Title'/><Value Type='Text'>"+ex+"</Value></Contains><Contains><FieldRef Name='Description' />"+"<Value Type='Text'>"+ex+"</Value></Contains></Or></Where></Query>";
var CAMLViewFields="<ViewFields><FieldRef Name='Title'/><FieldRef Name='Description'/> <FieldRef Name='ID'/></ViewFields>";
GetDataOnLoad(Query, CAMLViewFields);
}
function GetDataOnLoad(Query, CAMLViewFields) {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "List1",
CAMLQuery:Query,
CAMLViewFields:CAMLViewFields ,
completefunc: processResult
});
}
function processResult(xData, status) {
var counter = 0;
var newJqData = "";
debugger;
$(xData.responseXML).SPFilterNode("z:row").each(function () {
var JqData;
if (counter == 0) {
JqData="{"+'"id"'+":"+'"'+$(this).attr("ows_ID")+'",'+'"cell"'+":["+'"'+$(this).attr("ows_ID")+'",'+ '"'+$(this).attr("ows_Title")+'",'+ '"'
+$(this).attr("ows_Description")+'"'+"]}";
newJqData = newJqData + JqData;
counter = counter + 1;
} else {
var JqData="{"+'"id"'+":"+'"'+$(this).attr("ows_ID")+'",'+'"cell"'+":["+'"'+$(this).attr("ows_ID")+'",'+ '"'+$(this).attr("ows_Title")+'",'
+ '"'+$(this).attr("ows_Description")+'"'+"]}";
newJqData = newJqData +","+ JqData;
counter = counter + 1;
}
});
FinalDataForGrid(newJqData, counter);
}
function FinalDataForGrid(jqData, resultCount) {
debugger;
dataFromList = jqData.substring(0, jqData.length - 1);
var currentValue = jQuery("#list").getGridParam('rowNum');
var totalPages = Math.ceil(resultCount / currentValue);
var PageNumber = jQuery("#list").getGridParam("page"); // Current page number selected in the selection box of the JqGrid
newStr = "{"+'"total":'+'"'+totalPages+'",'+'"page":'+'"'+PageNumber+'",'+'"records":'+'"'+resultCount+'",'+'"rows":['+dataFromList+ "}]}";
var thegrid = jQuery("#list")[0];
var obj=JSON.stringify(newStr);
thegrid.addJSONData(JSON.parse(newStr));
}
</script>
<table id="list" width="100%" ></table>
<div id="pager" style="text-align:center;"></div>
I want to display data from SharePoint List using CAML Query, SPServices and JQGrid.
The data gets binded to the grid, I can see Page 1 of 2 and View 1-5 of 10. But When I click on next button, then Page 2 of 2 shows and view 6-10 of 10 shows up but data doesnt change. I am new to jqgrid, faced many issues even to bind grid, all are resolved right now except for pagination.

Related

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.

how to hide particular column when insert new record in kendo grid

hey hi everyone i am try to insert new record using kendo grid.
it's work fine.
but i want to set hide and show.
when its new then hide second column.
only on this row not other all.
here is my code:-
<!DOCTYPE html>
<html>
<head>
<link href="http://cdn.kendostatic.com/2012.3.1315/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1315/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://cdn.kendostatic.com/2012.3.1315/js/kendo.all.min.js"></script>
<script>
$(document).ready(function () {
var users = [{ UserId: 1, UserName: "Robin", IsAdmin: true }
, { UserId: 2, UserName: "Hood", IsAdmin: false }];
var t = $("#grid").kendoGrid({
dataSource: { data: users, pageSize: 10 }// binding data
,pageable: true
, selectable: "multiple row"
, toolbar: ["create"]
, columns: [
{ field: "UserId" }
, { field: "UserName"},
{ command: "destroy", title: " ", width: "100px" }
],
editable: true,
edit: function(e)
{
if(e.model.isNew())
{
$("td:nth-child(2)").css("display","none");
}
}
});
});
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type="button" value="Iterate" onclick="iterate()"/>
<div id="grid"></div>
</body>
</html>
please help if is possible when insert new record hide there second td.
thanks.
Try this,
Below code set in document.ready
$(".k-button,.k-button-icontext,.k-grid-add").click(function(){
var activityGrid = $("#grid").data("kendoGrid");
activityGrid.hideColumn(1);
});
Updated Code:
var cnt = 1;
$(".k-button,.k-button-icontext,.k-grid-add").click(function () {
cnt = 0;
});
var hideFieldName = "UserName";
$(".k-textbox").live("focusin", function (e) {
if (cnt == 0) {
if ($(this).attr("name") == hideFieldName) {
if ($(this).closest('tr').index() == cnt) {
$(this).attr("readonly", "readonly");
}
}
}
});
So, below code worked as per your requirement. But in this case textbox was generated but user can't enter any value.
Let me know if any issue....

jqGrid:: onclicking each row after editing another, saves the content but not restoring the edited row

the purpose is that after editing the text area in a line, and clicking on another row, the first one should get saved and the row should be restored. The code works till saving the record, but not restoring the edited row after saving.. Please help me to rectify the issue.
<?
if(isset($_GET)){
$startDate = $_GET['start_date'];
$endDate = $_GET['end_date'];
$type = $_GET['type'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" media="screen" href="../js/jqgrid/css/ui-lightness/jquery-ui-1.9.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="../js/jqgrid/css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" href="../js/powertip/jquery.powertip.css" />
<script type="text/javascript" src="../js/jqgrid/js/jquery1.8.3.js"></script>
<script type="text/javascript" src="../js/jqgrid/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="../js/powertip/jquery.powertip-1.1.0.min.js"></script>
<script type="text/javascript">
jQuery.jgrid.no_legacy_api = true;
</script>
<script src="../js/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<style>
.ratingDetails{
font-family:Arial;font-size:12px;color:#FFF;padding-left:2px;
}
</style>
</head>
<body>
<table id="rowed2"></table>
<div id="prowed2"></div>
<script>
jQuery(document).ready(function(){
var lastSel;
jQuery("#rowed2").jqGrid({
url:'feedbacks_bookings_rated_pagination.php?start_date=<?=$startDate?>&end_date=<?=$endDate?>&type=<?=$type?>',
datatype: "json",
height:"auto",
colNames:['Booking<br>Id','City','Customer name','Trip dates','Local Office','Rating','Action Taken','Status','Action'],
colModel:[
{name:'booking_id',index:'booking_id', width:45,align:"center",hidden:false,key: true},// key: true - to get the id value in POST
{name:'pick_city',index:'pick_city', width:90,align:"left"},
{name:'actual_name',index:'add_driver_number', width:130,align:"left",sortable:true},
{name:'tripdates',index:'tripdates', width:80,align:"center",sortable:false},
{name:'office_name',index:'office_name', width:150,align:"left",sortable:true},
{name:'rating_status',index:'rating_status', width:70,align:"center",sortable:true,title: false},
{name:'action_taken',index:'action_taken', width:220,align:"left",sortable:false,editable:true,edittype:'textarea',editoptions:{rows:"3",cols:"35"}},
{name:'img_action_status',index:'img_action_status', width:40,align:"center",sortable:true},
{name:'act',index:'act',width:100,align:'center',sortable:false}
],
rowNum:15,
rowList:[15,25,50],
pager: '#prowed2',
sortname: 'driver_name',
viewrecords: true,
sortorder: "asc",
subGrid : true,
subGridUrl: 'feedbacks_bookings_rated_pagination.php?booking=424519',
subGridModel: [{
name:['Booked on','Trip Type/ Amount','Driver Details','Local Office Phone','Essential Feedbacks','Other Feedbacks'],
width: [90,90,130,100,160,200]}
],
onSelectRow:
function(id){
//alert(lastSel+"-hi-"+id);
if(id && id!==lastSel){
if (typeof lastSel !== "undefined") {
jQuery("#rowed2").jqGrid('saveRow',lastSel);
jQuery("#rowed2").jqGrid('restoreRow',lastSel);
//jQuery("#rowed2").trigger("reloadGrid");
}
lastSel = id;
}
jQuery(this).jqGrid('resetSelection');
jQuery(this).editRow(id, true);
},
editurl: "feedbacks_bookings_rated_pagination.php",
caption:"Edit Feedback Details",
});
// icons in pagination frame bottom
jQuery("#rowed2").jqGrid('navGrid','#prowed2',{ add: false, edit: true,save: true, del: false, reload: true});
jQuery.fn.editRow = function(param) {
var rowid = param;
var booking_id = jQuery("#rowed2").jqGrid ('getCell', param, 'booking_id');
jQuery("#rowed2").jqGrid('editRow',rowid, {
keys : true,
oneditfunc: function() {
}
});
};
jQuery.fn.saveRow = function(param) {
var rowid = param;
jQuery("#rowed2").jqGrid('saveRow',rowid, {
successfunc: function(response) {
//obj = eval('(' + response.responseText + ')');
//$.jgrid.info_dialog('Status','<div class="ui-state-successr"><br>'+obj.responseText +'<br></div>', $.jgrid.edit.bClose,{buttonalign:'center'});
return true;
},
url : "feedbacks_bookings_rated_pagination.php",
mtype : "POST",
});
};
jQuery.fn.restoreRow = function(param) {
var rowid = param;
alert("rstore-"+rowid);
jQuery("#rowed2").jqGrid('restoreRow',rowid, {
afterrestorefunc : function( response ) {
alert("aaaa");
obj = eval('(' + response.responseText + ')');
$.jgrid.info_dialog('Status','<div class="ui-state-successr"><br>'+obj.responseText +'<br></div>', $.jgrid.edit.bClose,{buttonalign:'center'});
return true;
}
});
};
})
function closeAction(bkId){
if(confirm("Are you sure to close the action?")){
//Ok button pressed...
$.post('feedbacks_bookings_rated_pagination.php?action=close',{booking_id: bkId},
function(response){
alert(response.responseText);
$("#rowed2").trigger("reloadGrid");
return true;
},
"json"
);
}
}
// Function to display rating crieteria values as a tooltip on mouseover of Rating caption
function showRatingDetailsToolTip(id) {
$('#rating'+id).data('powertiptarget', 'tooltip'+id);
$('#rating'+id).powerTip({placement: 'e',smartPlacement: true,mouseOnToPopup: true});
}
</script>
</body>
</html>
Again.. given below a rectified code.. here also, the previous row not getting back from edit mode on clicking next row. Can you tell me the problem?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" media="screen" href="../js/jqgrid/css/ui-lightness/jquery-ui-1.9.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="../js/jqgrid/css/ui.jqgrid.css" />
<script type="text/javascript" src="../js/jqgrid/js/jquery1.8.3.js"></script>
<script type="text/javascript" src="../js/jqgrid/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript">
jQuery.jgrid.no_legacy_api = true;
</script>
<script src="../js/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
</head>
<body>
<table id="rowed2"></table>
<div id="prowed2"></div>
<script>
jQuery(document).ready(function(){
var lastSel;
jQuery("#rowed2").jqGrid({
url:'feedbacks_bookings_rated_pagination.php?start_date=<?=$startDate?>&end_date=<?=$endDate?>&type=<?=$type?>',
datatype: "json",
height:"auto",
colNames:['Booking<br>Id','City','Customer name','Trip dates','Local Office','Rating','Action Taken','Status','Action'],
colModel:[
{name:'booking_id',index:'booking_id', width:45,align:"center",hidden:false,key: true},// key: true - to get the id value in POST
{name:'pick_city',index:'pick_city', width:90,align:"left"},
{name:'actual_name',index:'add_driver_number', width:130,align:"left",sortable:true,editable:true,edittype:'text'},
{name:'tripdates',index:'tripdates', width:80,align:"center",sortable:false},
{name:'office_name',index:'office_name', width:150,align:"left",sortable:true},
{name:'rating_status',index:'rating_status', width:70,align:"center",sortable:true,title: false},
{name:'action_taken',index:'action_taken', width:220,align:"left",sortable:false,editable:true,edittype:'textarea',editoptions:{rows:"3",cols:"35"}},
{name:'img_action_status',index:'img_action_status', width:40,align:"center",sortable:true},
{name:'act',index:'act',width:100,align:'center',sortable:false}
],
rowNum:15,
rowList:[15,25,50],
pager: '#prowed2',
sortname: 'booking_id',
viewrecords: true,
sortorder: "asc",
onSelectRow:
function(id){
if(id && id!==lastSel){
if (typeof lastSel !== "undefined") {
jQuery("#rowed2").jqGrid('saveRow',lastSel,{url : "feedbacks_bookings_rated_pagination.php",mtype : "POST"});
jQuery(this).jqGrid('editRow',lastSel, false);
}
lastSel = id;
}
jQuery(this).jqGrid('editRow',id, true);
},
editurl: "feedbacks_bookings_rated_pagination.php",
caption:"Edit Feedback Details",
});
// icons in pagination frame bottom
jQuery("#rowed2").jqGrid('navGrid','#prowed2',{ add: false, edit: false,save: false, del: false, reload: true});
})
</script>
</body>
</html>
=====================
At last I could find the real problem.
It is not with the content of 'action_taken' field, but with the just previous field. In that I put a table inside a hidden DIV under the actual content, used for a tooltip content.
What happens is that after editing the action_taken field in next column and the server response is received, the edited content of 'action_taken' field was set to the content and title of the first TD of this table in previous column. Also, the edited column does not return from edit mode. If I remove the table from previous column, everything works ok. I tried with different id/style class for the table, but no change. What could be the problem? The table structure in previous column causing the issue is given below.
<table id='ratingdata32380' width='189' border='0' cellpadding='0' cellspacing='0' bordercolor='#000000' bgcolor='#4f9de2'>
<tr><td align='left' valign='middle' class='ratingDetails'>Was On Time?</td><td align='center' valign='middle' class='ratingDetails'>aaaa</td></tr>
</table>
The class 'ratingDetails' is nothing but just the font definition.
.ratingDetails{font-family:Arial;font-size:12px;color:#FFF;padding-left:2px;}
Any idea ?
You should decide which behavior should have your grid. You you want save the data from the previously editing row then you should call saveRow. If you want to discard the current changes and to restore the previous one you should call restoreRow. Calling of restoreRow after saveRow like you do currently inside of onSelectRow callback has no sense.
So if I understand correctly what you want to implement you should remove the line with saveRow which is before calling of restoreRow.

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.

jgGrid not showing data using asp.Net MVC 3.0

I am having a problem showing json data returned from my view in jgGrid 4.0
in the head section I have
<script src="/Scripts/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.lazyload.min.js" type="text/javascript"></script>
<script src="/Scripts/global.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
the body
$(document).ready(function () {
jQuery("#grid").jqGrid({
url: '#Url.Action("getusers", "dashboard",new {area="Security"})',
datatype: "json",
mtype: "GET",
colNames: ['Id', 'UserName'],
colModel: [
{ name: 'Id', index: 'Id',width: 200, align: 'left'},
{ name: 'UserName', index: 'UserName', width: 200, align: 'right' }
],
rowList: null,
pgbuttons: false,
pgtext: null,
viewrecords: false,
page:false,
caption: "Users"
});
});
here the Action code returning a json
public JsonResult GetUsers()
{
var repo = ObjectFactory.GetInstance<IRepository<User>>();
var result = (from x in repo.Query(x => x.ApplicationName == "DBM") select new {Id=x.Id, UserName=x.UserName}).ToArray();
return this.Json(result, JsonRequestBehavior.AllowGet);
}
}
I tested in both firefox and IE 9 the grid renders empty, no errors in firebug and data looks OK.
any hints would be appreciated.
jqGrid requires a specifc json format:
try this
var jsonData = new
{
total = (rowcount + paging.Size - 1) / paging.Size
page = paging.Page,
records = rowcount,
rows = (
from x in repo.Query(x => x.ApplicationName == "DBM")
select new
{
id=x.Id,
cell = new string[]
{
// the order of the columns here must match
x.Id,
x.UserName
}
})
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
See using jquery grid with asp.net mvc

Resources