Datainit is giving null - jqgrid

Can somebody please help me understand why the dataInit function wouldn't have a value for the field. I have the following added to the categories column in my grid.
dataInit: function (elem)
{
var v = $(elem).val();
alert("In data init val is " + v);
$(elem).trigger('change');
}
I get a null value in the alert and the trigger function doesn't fire either.

If this question about editoptions and using server data. I have got the answer. This is happen because your data is not local but from server. Using server(not local data), browser need several time to load into the select element and change to the selected option as in row.
So, the $(elem).val(); from dataInit is null because it is still null on that time, u have to wait about 100 ms(on my case).
Here my code, the case is about loading provinces with its cities on .
dataInit: function (elem) {
$(elem).ready(loadCities);
},
I create function loadCities function out of jqgrid definition
function loadCities() {
setTimeout('$.ajax({type: "GET",data: "", url: "<?php echo base_url();?>index.php/cities/cities_select_options_by_prov_and_store/"+$("#province").val()+"/"+$("#id").val(), success: function(data){ $("#city").html(data);}})',100);
}
here are my complete code
var gridStores = jQuery('#gridStores');
function loadCities() {
setTimeout('$.ajax({type: "GET",data: "", url: "<?php echo base_url();?>index.php/cities/cities_select_options_by_prov_and_store/"+$("#province").val()+"/"+$("#id").val(), success: function(data){ $("#city").html(data);}})',100);
}
var resetCitiesValues = function () {
gridStores.setColProp('#city', { editoptions: { value: ':- Choose Province First -'} });
};
gridStores.jqGrid({
url:'<?php echo base_url();?>index.php/stores/stores_json',
datatype: 'json',
colNames:['ID','Name'],
colModel:[
{name:'id',index:'stores.id', hidden:true,editable:true},
{name:'province',index: 'provinces.name', width:100,stype:'text',sorttype:'text',editable:true,editrules:{required:true},edittype:"select",editoptions:{dataUrl:'<?php echo base_url();?>index.php/provinces/provinces_select_options',
dataInit: function (elem) {
$(elem).ready(loadCities);
},
dataEvents: [{type: 'change',fn: function(e) {$.ajax({type: "GET",data: "", url: "<?php echo base_url();?>index.php/cities/cities_select_options/"+$(this).val(), success: function(data){ $("#city").html(data);}})}}]}},
{name:'city',index: 'cities.name', width:100,stype:'text',sorttype:'text',editable:true,editrules:{required:true},edittype:"select", editoptions:{ value: ':- Choose Province First -', defaultValue:'- Choose City -'}},
],
width:'600',
rownumbers: true,
rownumWidth: 40,
rowNum:10,
rowList : [20,30,50],
viewrecords: true,
pager: '#pagerStores',
sortname: 'stores.id',
sortorder: "desc",
searchOn:"false",
editurl: "<?php echo base_url();?>index.php/stores/edit"
});
jQuery("#gridStores").jqGrid('navGrid','#pagerStores',
{
edit:true,
add:true,
del:true,
search:false,
refresh:true,
recreateForm:true,
viewPagerButtons:false
},
{
closeAfterEdit:true,
closeAfterAdd:true,
reloadAfterSubmit:true,
editData: {<?php echo $this->security->get_csrf_token_name()?>: '<?php echo $this->security->get_csrf_hash() ?>'},
recreateForm:true,
viewPagerButtons:false
},
{
closeAfterEdit:true,
closeAfterAdd:true,
reloadAfterSubmit:true,
editData: {<?php echo $this->security->get_csrf_token_name()?>: '<?php echo $this->security->get_csrf_hash() ?>'}
},
{
delData: {<?php echo $this->security->get_csrf_token_name()?>: '<?php echo $this->security->get_csrf_hash() ?>'},
},
{
caption: "Search",
Find: "Find",
Reset: "Reset",
sopt : ['eq', 'cn'],
matchText: " match",
rulesText: " rules",
stringResult: true
}
);
jQuery("#gridStores").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});

I have the same problem too. In order to accomplish this: jqgrid incorrect select drop down option values in edit box in dataInit and dataEvents v = $(elem).val(); and var v = parseInt($(e.target).val(), 10); give me back null. If i put in v the right values all the other works fine!

The elem is now already an object, so JQuery is not needed to get its properties.
Just use var v = elem.value;

Related

Cancel edit event in jqGrid inline edit

I'm using jqgrid inline edit in which i have a scenario to invoke the "cancel edit" button event and throw a message "Are you sure to cancel?".
//Code:
//Unload the grid.
$('#CommentsData').jqGrid('GridUnload');
//Comments grid start.
$("#CommentsData").jqGrid({
datastr: tableSrc,
hoverrows: false,
datatype: "jsonstring",
jsonReader: {
id: 'CommentId',
repeatitems: false
},
height: 'auto',
width: 'auto',
hidegrid: false,
gridview: true,
sortorder: 'desc',
sortname: 'DateTime',
pager: '#CommentsPager',
rowList: [], // disable page size dropdown
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: false, // disable current view record text like 'View 1-10 of 100'
caption: "Comments",
colNames: ['DateTime', 'UserName', 'Comments'],
colModel: [
{
name: 'DateTime', index: 'DateTime', width: 120, formatter: "date", sorttype: "date",
formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i A" }
},
{ name: 'UserName', index: 'UserName' },
{ name: 'CommentText', index: 'CommentText', editable: true }],
//Events to add and edit comments.
serializeRowData: function (postdata) {
var filterResult;
var jsonResult;
if (tableSrc == "")
jsonResult = $.parseJSON(commentDetails);
else
//Parse values bind to the comments.
jsonResult = $.parseJSON(tableSrc);
var newResult = new Object();
//Check if operation is edit.
if (postdata.oper == "edit") {
//Filter the edited comments from main source.
newResult = Enumerable.From(jsonResult).Where(function (s) { return s.CommentId = postdata.id }).First();
newResult.CommentText = postdata.CommentText;
}
else {
filterResult = Enumerable.From(jsonResult).First();
newResult.CommentText = postdata.CommentText;
newResult.TransactionId = filterResult.TransactionId;
newResult.TaskId = filterResult.TaskId;
}
filterResult = JSON.stringify(newResult);
$.ajax({
url: '#Url.Action("UpdateComments", "Home")',
datatype: 'json',
data: { 'resultData': filterResult, 'action': postdata.oper },
type: 'POST',
success: OnCompleteComments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
//After update Load the grid.
function OnCompleteComments(result) {
selectTaskComment = false;
$('#dialog').dialog("close");
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
rowList = $('.ui-pg-selbox').val();
Loadgrid($("#TransactionsGrid").getGridParam('page'));
}
},
onSelectRow: function (id) {
selectTaskComment = true;
var thisId = $.jgrid.jqID(this.id);
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
var selectValues = jQuery('#CommentsData').jqGrid('getRowData', id);
thisId = $.jgrid.jqID(this.id);
if (selectValues.UserName == '#ViewBag.UserName' || '#ViewBag.IsAdmin' == 'True') {
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
}
else {
$("#" + thisId + "_iledit").addClass('ui-state-disabled');
$("#del_" + thisId).addClass('ui-state-disabled');
}
}
});
jQuery("#CommentsData").jqGrid('navGrid', '#CommentsPager', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {},
{
//Delete event for comments
url: '#Url.Action("UpdateComments", "Home")',
serializeDelData: function (postData) {
return {
resultData: JSON.stringify(postData.id),
action: JSON.stringify(postData.oper),
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
beforeSubmit: function () {
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
return [true, '', ''];
},
afterSubmit: function (response, postdata) {
selectTaskComment = false;
Loadgrid($("#TransactionsGrid").getGridParam('page'));
return [true, '', ''];
}
});
$('#CommentsData').jqGrid('inlineNav', '#CommentsPager', { edit: true, add: true, save: true, del: false, cancel: true });
$("#CommentsData_iledit").addClass('ui-state-disabled');
$("#del_CommentsData").addClass('ui-state-disabled');
In which event i have to write the code and throw the alert message?
Also if possible, need to know if the above code could be optimized. Because the delete event is written in a separate place comparing edit and add. I'm bit confused if this is right method.
The easiest way to invoke the "cancel edit" button would be executing the code
$("#CommentsData_ilcancel").click(); // trigger click event on Cancel button
where CommentsData is the id of the grid.

Retain filter text in filter toolbar on grid reload

I'm using jqgrid in which i'm trying to retain the filter text after the grid reload.
I have cell update functionality,
//Code:
$.ajax({
url: '#Url.Action("UpdateComments", "Home")',
datatype: 'json',
data: { 'resultData': filterResult, 'action': postdata.oper },
type: 'POST',
success: OnCompleteComments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
//After update Load the grid.
function OnCompleteComments(result) {
myfilter = $('#TransactionsGrid').jqGrid("getGridParam", "postData").filters;
Loadgrid($('#TransactionsGrid').getGridParam('page'));
}
After the successful udpate of the cell i'm reloading the grid for the cell to reflect the udpated values. In the OnComplete i'm getting the filter assigned to a golbally declared variable(myfilter).
//Grid:
datatype: 'local',
hoverrows: false,
colNames: colHeader,
colModel: colname,
localReader: { id: 'TransactionId' },
rowNum: 10,
hidegrid: false,
rownumbers: true,
pager: '#TransactionsGridPager',
viewrecords: true,
caption: "Transaction Details",
height: 'auto',
scrollOffset: 0,
page: PageNumber,
gridview: true,
shrinkToFit: true,
autoencode: true,
ignoreCase: true,
mySelection: {},
onInitGrid: function () {
// get reference to parameters
var p = $(this).jqGrid("getGridParam");
// set data parameter
p.data = gridData.BuildTransactionsDataTable;
},
In grid reload(ajax function is called), once the grid is loaded i'm re assigning the filter. In this place i'm getting the filtered results in the grid exactly bu the text which i used to filter the results is not in the filter toolbar. Its empty.
GridReload(Retain filter):
jQuery("#TransactionsGrid").jqGrid({
});
if (myfilter) {
var searchFiler = JSON.parse(myfilter).rules[0].data, grid = $("#TransactionsGrid"), f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
}
f = { groupOp: "OR", rules: [] };
f.rules.push({ field: JSON.parse(myfilter).rules[0].field, 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 }]);
}
Now i need the filtered text to be retained in the filter toolbar. how can i achieve this?

Add check boxes in Jquery grid view

I have the following code in page which binds the data to j query grid.
Now i want to add one more column for check-boxes to the existing grid and when i select some check boxes and press some button .. i need to get the selected row values .
I have seen some tutorials for this they mentioned about some formatter .... but they are not clear
Please help me to achieve this.
Thanks in advance.
Code:
$(document).ready(function () {
$("#btn_GenerateEmpList").click(function () {
var firstClick = true;
if (!firstClick) {
$("#EmpTable").trigger("reloadGrid");
}
firstClick = false;
var empId= $("#txt_emp").val();
$.ajax({
type: "POST",
url: "PLBased.aspx/GetEmpNames",
data: JSON.stringify({ empId: empId}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
result = result.d;
jQuery("#EmpTable").jqGrid({
datatype: "local",
colNames: ['Emp Name'],
colModel: [
{ name: "EmpName", Index: "EmpName", width: 80 }
],
data: JSON.parse(result),
rowNum: 10,
rowList: [5, 10, 20],
pager: '#pager',
loadonce: false,
viewrecords: true,
sortorder: 'asc',
gridview: true,
autowidth: true,
sortname: 'EMPID',
height: 'auto',
altrows: true,
});
},
error: function (result) {
alert("There was some error ");
}
});
});
});
You can use customformatter to show checkbox in the column. For this, you can write the code as below in your jqGrid Code.
colNames: ['Id','Emp Name','Emp Checkbox'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'EmpName', Index: 'EmpName', width: 80 },
{ name: 'Empchk', Index: 'Empchk', width: 50, align: 'center', editable: true, edittype: "checkbox", editoptions: { value: "true:false" },
formatter: generateEmpCheckBox, formatoptions: { disabled: false } }
],
formatter function code as below,
function generateEmpCheckBox(cellvalue, options, rowObject) {
var checkedStr = "";
if (cellvalue == true) {
checkedStr = " checked=checked ";
}
return '<input type="checkbox" onchange="UpdateEmpcheckbox(' + rowObject.Id + ',this)" value="' + cellvalue + '" ' + checkedStr + '/>';
}
function UpdateEmpcheckbox(selectedId, chkBox) {
if ($(chkBox).prop("checked")) {
//you can write an ajax here, to update the server
//when the checkbox is checked
}
else if (!($(chkBox).prop("checked"))) {
//you can write an ajax here to update the server
//when the checkbox is unchecked
}
return false;
}
Set the option multiselect:true which will add column of checkboxes. Then add
$('#EmpTable').jqGrid('getGridParam', 'selarrrow')
will return an array of selected id's.

load jqgrid via ajax to dialog search options dropdown don't work

When I use my jqgrid (v.4.6) on page evrything is ok.
When I load jqgrid via ajax to jquery dialog searchoptions dropdown list doesn't work for me.
In jqgrid search box searchoptions dropdown list doesn't work for me either.
$(document).ready(function(){
jQuery("#list_bs").jqGrid({
url:'some.php',
datatype: "json",
height: 450,
width: 1050,
colNames:['FirstName','Name','Date'],
colModel:[
{name:'FirstName',index:'FirstName', width:200, sorttype:'string', searchoptions:{sopt:['bw','bn','cn','ne','ew','en']}},
{name:'Name',index:'Name', width:200, sorttype:'string', searchoptions:{sopt:['bw','bn','cn','ne','ew','en']}},
{name:'Date',index:'Date', width:100, sorttype:'string', searchoptions:{sopt:['bw','bn','cn','ne','ew','en']}},
],
rowNum:50,
rowList : [20,30,50],
loadonce:false,
multiselect : false,
mtype: "GET",
shrinkToFit: false,
rownumbers: true,
gridview: true,
pager: '#pager',
sortname: 'Name',
viewrecords: true,
sortorder: "ASC",
toolbar: [true,"top"],
});
$("#list_bs").jqGrid('navGrid', '#pager_bs',
{
edit:false,
add:false ,
del:false,
},
{},
{},
{},
{
multipleSearch: true,
showQuery: true
}
......
)
});
jQuery("#list_bs").jqGrid('filterToolbar',{ searchOperators: true,stringResult:true, searchOnEnter: false, autosearch: true ,enableClear: false});
try like below this work for me.You have give data in the dropdown in its column model
{
name: 'Name', Name: 'Title', align: 'center', editable: true, editoptions: { readonly: 'readonly' },
stype: 'select',
searchoptions: {
sopt: ['eq','cn'],
dataUrl: //get data from server
buildSelect: function (data) {
var response, s = '<select>', i;
response = jQuery.parseJSON(data);
s += '<option value="0">--Select Book Title--</option>';
if (response && response.length) {
$.each(response, function (i) {
s += '<option value="' + this.Name+ '">' + this.Name+ '</option>';
});
}
return s + '</select>';
}
}
}
I don't need dropdown in toolbar input
My search operator dropdown list doesn't open.
The problem is only when my own jqgrid is loaded by ajax in to jquery dialog.
$( "#my_dialog" ).dialog({
width:'auto',
open: function(event, ui){
$.ajax(
{
url: "some.php",
type: "POST",
data: "is_dialog=true",
error: function(){
},
beforeSend: function(){
$("#loader").show();
},
complete: function(){
$("#loader").hide();
},
success: function( strData ){
$("#dialog_content").html(strData );
}
}
);
},
});
...........
<div id="my_dialog" >
<div id="dialog_content"></div>
</div>

Jqgrid treegrid performance

I have tried gridview:ture , loadui:block but still it takes more time to display treegrid after loading. my json contains more then 2044 data. I am using firefox version 3.6
my code is given below
**
Glcm= [{name:'id',index:'id', label:'Id',hidden:true,key:true, Enabled:false,jsonmap:"id"},{name:'text',index:'text',label:'Global Ledger',width:400,jsonmap:"text",formatter:gLCheckbox},{name:'additionalInfo',index:'additionalInfo',label:'additionalInfo',hidden:true,jsonmap:"additionalInfo"},
],
**
GlTree.jqGrid({
url: 'GlTreeStructure.action',
datatype: "json",
mtype: "POST",
colModel:Glcm,
width:outerwidthGL,
height:300,
rowNum:-1,
pager: '#ptreeList',
viewrecords: true,
caption:"Global Ledger",
toolbar: [true,"top"],
gridview:true,
treeGrid: true,
pginput:false,
pgtext:"",
pgbuttons:false,
loadui:'block',
deepempty:true,
ignoreCase: true,
autoencode:true,
jsonReader :{root: 'glList',
cell:"",
repeatitems: false
},
treeReader : {
level_field: "level",
left_field:"lft",
right_field: "rgt",
leaf_field: "isLeaf",
parent_id_field: "parentId",
expanded_field: "expanded",
loaded: "loaded"
},
treedatatype: "json",
treeGridModel:'adjacency',
ExpandColClick: true,
loadonce:true,
ExpandColumn : 'text',
// cellSubmit: 'remote',
gridComplete:function()
{
myData = GlTree.jqGrid('getRowData');
}
});
// this function is used in formatter to display radio buttons
function gLCheckbox(amount,options,rData)
{
if(rData.additionalInfo === 'G')
return '<div id ="checkglId"><input type="radio" id="radioId" name ="radioName" value="' +rData.text+'" align = "center",offval="off" onclick="selectGLElement(\''+rData.id+'\');" /> '+amount + '</div>';
else
return amount;
}
I finally got the answer for my question. I am now able to auto large number of data into treegrid.
I have used treegrid adjaceny model aud autoloaded the tree on demand. But my treenode gets loaded on onSelectRow.
onSelectRow: function(id){
var data = $(this).jqGrid("getRowData", id);
getChildTree(data,data.glId);
}
function getChildTree(postdata,id)
{
$.ajax({
type: "GET",
url: "GlChildTreeStructure.action?glId="+id,
dataType: "json",
success: function(json){
JsonDataObj = json;
for(var i=0;i<JsonDataObj.ChildTreeList.length;i++){
if(JsonDataObj.ChildTreeList.isLeaf==true){
//alert("JsonDataObj.ChildTreeList : "+JsonDataObj.ChildTreeList[i].glId)
$("#GlTreeStructureGrid").jqGrid("addChildNode",JsonDataObj.ChildTreeList[i].glId, JsonDataObj.ChildTreeList[i].parentId,
{
"glId":JsonDataObj.ChildTreeList[i].glId,
"text":JsonDataObj.ChildTreeList[i].text,
"additionalInfo":JsonDataObj.ChildTreeList[i].additionalInfo,
"alternativeParent":JsonDataObj.ChildTreeList[i].alternativeParent,
"parentId":JsonDataObj.ChildTreeList[i].parentId,
"parent":JsonDataObj.ChildTreeList[i].parentId,
"dataType":JsonDataObj.ChildTreeList[i].dataType,
"periodType":JsonDataObj.ChildTreeList[i].periodType,
"glPresentationOrder":JsonDataObj.ChildTreeList[i].glPresentationOrder,
"extendedLink":JsonDataObj.ChildTreeList[i].extendedLink,
"parentCalculation":JsonDataObj.ChildTreeList[i].parentCalculation,
"isLeaf":JsonDataObj.ChildTreeList[i].isLeaf,
"level":JsonDataObj.ChildTreeList[i].level,
"lft":JsonDataObj.ChildTreeList[i].lft,
"expanded":JsonDataObj.ChildTreeList[i].expanded,
"loaded":JsonDataObj.ChildTreeList[i].loaded,
"icon":JsonDataObj.ChildTreeList[i].icon,
"rgt":JsonDataObj.ChildTreeList[i].rgt});
}else{
// alert("JsonDataObj.ChildTreeList : "+JsonDataObj.ChildTreeList[i].glId)
$("#GlTreeStructureGrid").jqGrid("addChildNode",JsonDataObj.ChildTreeList[i].glId, JsonDataObj.ChildTreeList[i].parentId,
{
"glId":JsonDataObj.ChildTreeList[i].glId,
"text":JsonDataObj.ChildTreeList[i].text,
"additionalInfo":JsonDataObj.ChildTreeList[i].additionalInfo,
"alternativeParent":JsonDataObj.ChildTreeList[i].alternativeParent,
"parentId":JsonDataObj.ChildTreeList[i].parentId,
"dataType":JsonDataObj.ChildTreeList[i].dataType,
"parent":JsonDataObj.ChildTreeList[i].parentId,
"periodType":JsonDataObj.ChildTreeList[i].periodType,
"glPresentationOrder":JsonDataObj.ChildTreeList[i].glPresentationOrder,
"extendedLink":JsonDataObj.ChildTreeList[i].extendedLink,
"parentCalculation":JsonDataObj.ChildTreeList[i].parentCalculation,
"isLeaf":JsonDataObj.ChildTreeList[i].isLeaf,
"level":JsonDataObj.ChildTreeList[i].level,
"lft":JsonDataObj.ChildTreeList[i].lft,
"expanded":JsonDataObj.ChildTreeList[i].expanded,
"loaded":JsonDataObj.ChildTreeList[i].loaded,
"icon":JsonDataObj.ChildTreeList[i].icon,
"rgt":JsonDataObj.ChildTreeList[i].rgt});
}
}
},
});
}

Resources