Not loading json data in jqgrid - javascript

Why json data not loading in jqgrid ?
I am using ASP.net with C# with JQGrid using javascript & AJAX
Here is my code below :
public string Alarm_Main()
{
SqlConnection con = new SqlConnection(ConnString);
DataTable dt = new DataTable();
con.Open();
string query = "select * from MST_ALARM_TYPE";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
return JsonConvert.SerializeObject(ds.Tables[0]);
}
In file : DataService.aspx the code is given below :
<script>
$(function () {
$("#list").jqGrid({
url: 'DataService.asmx/Alarm_Main',
datatype: 'json',
mtype: 'POST',
serializeGridData: function (postData) {
alert(JSON.stringify(postData));
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json;charset=utf-8;" },
loadonce: true,
jsonReader: {
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
root: function (obj) { return obj.d; },
repeatitems: false,
id: "0"
},
colNames: ['', '알람코드', '등록날짜', '알람명', '등록자', ''],
colModel: [
{ name: 'myradio', width: 30, search: false, fixed: true, align: 'center', resizable: false, sortable: false, frozen: true, formatter: function (cellValue, option) { return '<input type="radio" name="radio_' + option.gid + '"/>'; }, frozen: true },
{ name: 'alarm_type_code', index: 'alarm_type_code', align: 'center', width: 200, frozen: true, sorttype: 'number' },
{ name: 'regist_date', index: 'regist_date', width: 200, editable: true, frozen: true, align: 'center', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "Y-m-d", newformat: "Y-m-d" } },
{ name: 'alarm_type_name', index: 'alarm_type_name', width: 200, frozen: true },
{ name: 'regist_name', index: 'regist_name', width: 200, frozen: true },
{ name: 'myac', width: 50, search: false, fixed: true, sortable: false, resizable: false, fommatter: 'action', formatoptions: {keys:true}}
],
rowNum: 10,
rowList: [5, 10, 20, 50],
width: '100%',
pager: '#pager',
gridview: true,
rownumbers: false,
sortable: true,
multiselect: true,
scrollOffset: 0,
cellEdit: true,
sortorder: 'desc',
caption: '그리드 제목',
height: '100%',
shrinkToFit: true,
loadonce: true
});
jQuery("#list").jqGrid('setFrozenColumns');
jQuery("#list").trigger('reloadGrid');
jQuery("#list").jqGrid('navGrid', '#pager', { excel: true, add: true, edit: true, view: true, del: true, search: true, refresh: true },
{ closeAfterAdd: true, reloadAfterSubmit: false, closeOnEscape: true },
{ closeAfterAdd: true, reloadAfterSubmit: false, closeOnEscape: true },
{ reloadAfterSubmit: false, closeOnEscape: true },
{ multipleSearch: true, multipleGroup: true, showQuery: true, closeOnEscape: true, onSearch: function () { } }, { closeOnEscape: true });
jQuery("#list").jqGrid('bindKeys', { "onEnter": function (rowid) { alert("You enter a row with id:" + rowid) } });
jQuery("#list").jqGrid('navButtonAdd', '#pager', { caption: "Excel", onClickButton: function () { jquery("#list").jqGrid('excelExport', { url: 'D:\\' }); } });
jQuery("#list").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "cn" });
});
</script>
I can't see anything on my screen.
What can be the issue ?

Below is example , how to use ado.net with jqgrid, i hope this will help you.
Controller"
public ActionResult GetCustomer(int rows, string sidx, string sord, int page)
{
List<Customer> _customerList = new List<Customer>();
DataTable dt = new DataTable();
string strConString = #"Data Source=gen5win10;Initial Catalog=AsifDb;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConString))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Customer", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Customer cobj = new Customer();
cobj.CustomerId = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerId"].ToString());
cobj.ID = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerId"].ToString());
cobj.Name = ds.Tables[0].Rows[i]["Name"].ToString();
cobj.Phone = ds.Tables[0].Rows[i]["Phone"].ToString();
cobj.Address = ds.Tables[0].Rows[i]["Address"].ToString();
cobj.Date = Convert.ToDateTime(ds.Tables[0].Rows[i]["Date"].ToString());
_customerList.Add(cobj);
}
}
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var Results = _customerList.Select(
a => new
{
a.ID,
a.Name,
a.Phone,
a.Address,
a.Date,
});
int totalRecords = Results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
Results = Results.OrderByDescending(s => s.ID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
Results = Results.OrderBy(s => s.ID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
HTML:
<link href="~/Scripts/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.css" rel="stylesheet" />
<link href="~/Scripts/Guriddo_jqGrid_JS_5.2.0/css/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/jquery-1.11.0.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.js"></script>
<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/jquery.jqGrid.min.js"></script>
<h2>Customers</h2>
<br>
<script type="text/javascript">
$(document).ready(function () {
$('#sample').jqGrid({
datatype: 'Json',
url: '/Customer/GetCustomer',
type: 'POST',
colNames: ['ID', 'Name', 'Phone', 'Address', 'Date'],
colModel:
[
{key:true , name: 'ID', index: 'ID', editable: false },
{name: 'Name', index: 'Name', editable: true ,editoptions: {maxlength: 15 },editrules:{ required: true, }, },
{ name: 'Phone', index: 'Phone', editable: true, editoptions: { maxlength: 15, },editrules: { required: true, },},
{name: 'Address', index: 'Address', editable: true, editoptions: { maxlength: 30,}, editrules: {required: true,},},
{ name: 'Date', index: 'Date', editable: false, formatter: "date" },
],
pager: jQuery('#pager'),
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "record",
repeatitems: false,
Id: "0"
},
caption: 'Sample JqGrid Table',
viewrecords: true,
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
// multiselect: true
}).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true },
{
// edit options
url: '/Customer/EditCustomer',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response)
{
if (response.responseText) {
alert(response.responseText);
}
}
},
{
//add
url: '/Customer/AddCustomer',
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{ //Options for Delete
url:'/Customer/DeleteCustomer',
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response)
{
if (response.responseText) {
alert(response.responseText);
}
}
}
);
});
</script>
<table id="sample"></table>
<div id="pager"> </div>

Related

Empty Edit/Add windows on jQGrid for MVC

Although the jQGrid loads properly on the website, clicking the edit and add buttons brings up a window where I can't add the database information. It only shows the submit and cancel buttons on the bottom left.
I'm currently using this function for jQGrid:
$('#StudentGrid').jqGrid({
url: '#Url.Action("GetStudent", "Admin")',
editurl: '#Url.Action("GetStudent", "Admin")',
mtype: 'GET',
datatype: 'json',
iconSet: "fontAwesome",
caption: 'Database',
autoresizeOnLoad: true,
autoResizing: { compact: true },
prmNames: { page: "CurrentPage", rows: "PageSize" },
jsonReader: {
repeatitems: false,
id: "StudentId",
root: "rows",
page: "page",
total: "total",
records: "records"
},
hidegrid: false,
autowidth: true,
//width: 1250,
/*height: 800,*/
top:100,
gridView: true,
loadonce: true,
rowNum: 10,
scrollrows: true,
autoresizeOnLoad: true,
autoResizing: { compact: true },
viewrecords: true,
pager: '#pager',
pgbuttons: true,
colNames: ["StudentId", "Name", "Grade"],
colModel: [
{
name: 'studentId',
index: 'studentId',
editoptions: { readonly: 'readonly' },
width: 25,
hidden: false,
sortable: false
},
{
name: 'name',
index: 'name',
editoptions: { size: 25, maxlength: 20 },
hidden: false,
sortable: true,
width: 25,
align: "center"
},
{
name: 'grade',
index: 'grade',
hidden: false,
sortable: true,
width: 25,
align: "center"
}
],
postData: {
StudentId: $("studentId").val(),
Name: $("name").val(),
Grade: $("grade").val()
},
loadError: function (request, textStatus, errorThrown) {
handleError('An error occured trying to load the Database.', request, textStatus, errorThrown);
},
gridComplete: function () {
},
selectTimeout: 0, //for wait to prevent from onSelectRow event firing when actually it is a double click
onSelectRow: function (rowid, status, e) {
clearTimeout(this.selectTimeout);
this.selectTimeout = setTimeout(
function () {
if (status) {//select
;
}
else { //deselect
$('#StudentGrid').jqGrid("resetSelection");
}
},
250);
},
ondblClickRow: function (rowid, iRow, iCol, e) {
}
}).jqGrid('navGrid', '#pager', {
add: true,
del: true,
edit: true,
search: false,
refresh: false,
addfunc: function (id) {
updateRow("new");
},
editfunc: function (id) {
updateRow("edit");
},
delfunc: function (id) {
deleteRow(id);
}
}).jqGrid('gridResize', { minWidth: 1024, maxWidth: 2048, minHeight: 300, maxHeight: 450 });
Both the edit and add buttons use the following function:
//Add new record to grid or edit existing record.
function updateRow(id) {
var oper;
var rowData;
if (id == 'new') {
//add requested, set jqgrid value
oper = 'add';
}
else {
//edit requested, set jqgrid value
oper = 'edit';
//Get jqgrid row id
var rowId = $('#StudentGrid').getGridParam("selrow");
//Re-asign id to rowId
id = rowId
//Set row data
rowData = $('#StudentGrid').jqGrid('getRowData', rowId);
}
// Display the edit dialog below to the grid
var position = getDialogPosition();
$('#StudentGrid').editGridRow(id, {
top: position.top,
left: position.left,
width: 900,
height: 'auto',
mtype: 'POST',
modal: true,
autoresizeOnLoad: true,
autoResizing: { compact: true },
recreateForm: true,
closeAfterAdd: true,
closeAfterEdit: true,
reloadAfterSubmit: true,
ajaxOptions: { cache: false },
editData: {
StudentId: $("studentId").val(),
Name: $("name").val(),
Grade: $("grade").val()
},
onInitializeForm: function (form) {
$('input', form).keypress(
function (e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if (key == 13) {
e.preventDefault();
}
});
},
afterSubmit: function (response, postdata, formid) {
//if action canceled
var retObj = JSON.parse(response.responseText);
if (retObj && retObj.CancelAction > 0) {
alert(retObj.Message);
}
$("#StudentGrid").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid");
return [true, '', false]; // no error and no new rowid
},
afterComplete: function (response, postdata, formid) {
//Set fields to only readonly
$('#studentId').attr('readonly', 'readonly');
$("#StudentGrid").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid");
checkForError('An error occured trying to save Student record.', response, null, null, formid);
},
beforeShowForm: function (form) {
//Remove readonly - need to be editable when adding a new code value record to grid/db code values table
if (id == 'new') {
$('#studentId').removeAttr('readonly');
}
},
successfunc: function (data) {
return true;
},
beforeSubmit: function (postdata, formid) {
return [true];
}
});
}
The HTML for the table is:
<table style="width:90%;margin:5px;">
<tr style="vertical-align:top;">
<td>
<div style="margin-top:5px;"></div>
<div class="textborder">
<span>Student Database</span>
</div>
<table id="StudentId"></table>
<div id="pager"></div>
</td>
</tr>
</table>
This is my first time trying to use jQGrid, so are there any parts of the code I'm missing?
Not sure, but you should set your fields as editable. this is the property in colModel -> editable : true like this:
colModel: [
{
name: 'name',
index: 'name',
editable : true,
editoptions: { size: 25, maxlength: 20 },
hidden: false,
sortable: true,
width: 25,
align: "center"
},
....
Check the docs for editing

Controller return values but not show in JqGrid in ASP.NET Core

I am using jqgrid, controller return list of values but values are not showing on jqgrid. Rows created button groupid, and name not shown. I also use break point controller return datatable correctly but not show on jqgrid.
I also attach the screenshort you can see the actual result.
Controller
public JsonResult mfollowsummary(int id)
{
using (objSqlCon = new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("select Group_Id,Group_Name from Groups where Comp_Id=" + 1 + "", objSqlCon);
cmd.CommandType = CommandType.Text;
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
objSqlCon.Open();
sd.Fill(dt);
objSqlCon.Close();
string JSONString = JsonConvert.SerializeObject(dt);
var people = JsonConvert.DeserializeObject<List<Groups>>(JSONString);
return Json(people);
}
}
Screenshort
Return Result of function
Jqgrid Link
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.5/css/ui.jqgrid.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.5/jquery.jqgrid.min.js"></script>
Javascript
<script type="text/javascript">
jQuery(document).ready(function ($) {
var $grid = $("#jqGrid");
$grid.jqGrid({
url: '#Url.Action("mfollowsummary")',
datatype: 'json',
postData: {
},
jsonReader: { id: 'Group_Id' },
colModel: [
{ name: 'GroupId', width: 20, hidden: false, editable: true, editable: "disabled" },
{ name: 'GroupName', width: 200, frozen: true, editable: true, searchoptions: { sopt: ['cn'] } },
],
loadonce: true,
navOptions: {
reloadGridOptions: { fromServer: true }
},
formEditing: {
closeOnEscape: true,
closeAfterEdit: true,
savekey: [true, 13],
reloadGridOptions: {
fromServer: true
}
},
forceClientSorting: true,
viewrecords: true,
autowidth: true,
shrinkToFit:true,
height: 350,
rowNum: 100,
rowList: [10, 20, 30, 50, 100, 500],
pager: "#jqGridPager",
rownumbers: true,
sortname: 'Group_Name',
sortorder: 'Group_Name',
loadComplete: function () {
//$("tr.jqgrow:odd").css("background", "#f0f8ff");
},
});
$("#jqGrid").jqGrid("setFrozenColumns");
});
</script>
Result Screenshot
Return Function Result
HTML
<div class="table-responsive">
<table id="jqGrid" class="table"></table>
</div>
<div id="jqGridPager"></div>
You have only set coorect the id, but not the names. Your colModel names does not respect the data returned. Try with the following colModel.
colModel: [
{ name: 'Group_Id', width: 20, hidden: false, editable: true, editable: "disabled" },
{ name: 'Group_Name', width: 200, frozen: true, editable: true, searchoptions: { sopt: ['cn'] } },
],
Note names Group_Id, Group_Name, which corresponds to waht you return from the server.
JSON Response
JSON Response screenshort

After row saved call back in jqgrid

I need to able to tap into an event after row has been updated, I use inline editing. There is a beforeSend event in ajaxRowOptions but no matching after.
How do I implement an after save callback?
Here is my grid:
$('#myGrid').jqGrid({
datatype: 'local',
jsonReader: common.jqgrid.jsonReader('Code'),
editurl: common.getServerPath() + 'myAjax/updateSomething/',
ajaxRowOptions: {
beforeSend: function (jqXhr, settings) {
//something here
}
}
},
mtype: 'POST',
pager: '#myPager',
colNames: ['Method', 'Type', 'Package', 'Disc %'],
colModel: [
{
name: 'Code',
index: 'Code',
width: 25,
sortable: false
},
{
name: 'MethodType',
index: 'MethodType',
width: 10,
sortable: false,
align: 'center'
},
{
name: 'ProfNo',
index: 'ProfNo',
width: 15,
sortable: false,
align: 'center'
},
{
name: 'Discount',
index: 'Discount',
width: 15,
sortable: false,
edittype: 'text',
align: 'right',
editable: true,
editrules: {
number: false,
custom: true,
custom_func: validateDiscount
}
}],
scroll: true,
hidegrid: false,
altRows: true,
altclass: 'gridAltRowClass',
height: 330,
scrollOffset: 0,
width: 770,
rowNum: 500,
footerrow: true,
userDataOnFooter: true
});
and
validateDiscount: function (value) {
if (isNaN(value)) {
return [false, 'Discount must be a number.'];
}
else {
var numValue = parseFloat(Number(value).toFixed(2));
if (numValue >= 100.00) {
return [false, 'is not a valid value. Discount must be a number less than 100.'];
}
}
return [true, ''];
},

JQGrid displaying wrong date when formatted

I have a JQGrid that is built using a jsonReader, with a field called quote_date.
When this field is not formatted, it displays the value "19/04/2020 00:00:00"
Code for unformatted field
name: 'quote_date', index: 'quote_date', width: 100, editable: true
However when I try to use the JQGrid formatter (I am trying to remove the trialing zero's), the date value in the grid is disaplyed as "10-10-2024" !
Here is the code I am using to format the field
name: 'quote_date', formatter: 'date', datefmt: "d-M-Y", editoptions: { dataInit: initDateEdit }, formatoptions: { srcformat: "ISO8601Long", newformat: "d-m-Y" }, index: 'quote_date', width: 100, editable: true
The expected result is "19/04/2020"
I have check the returned JSON result and that is correct as per the below.
Here is my complete code to give some context.
Code to build grid
function LoadGrid() {
jQuery("#jqquotes").jqGrid({
url: '../WebService1.asmx/getDataQuotes',
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) {
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
repeatitems: false
},
loadComplete: function () {
//alert("OK");
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
onSelectRow: showDetailsGrid,
height: 'auto',
//autowidth: true,
rowNum: 30,
rowList: [10, 20, 30],
colNames: ['Doc ID', 'Quote #', 'Date', 'Customer'],
colModel: [
{ name: 'docid', key: true, index: 'docid', width: 55, editable: true },
{ name: 'quote_number', index: 'quote_number', width: 90, editable: true },
{
name: 'quote_date', formatter: 'date', datefmt: "d-M-Y", editoptions: { dataInit: initDateEdit },
formatoptions: { srcformat: "ISO8601Long", newformat: "d-m-Y" }, index: 'quote_date', width: 100, editable: true
//name: 'quote_date', index: 'quote_date', width: 100, editable: true
},
{
name: 'cust_name', index: 'cust_name', width: 80, align: "left", editable: true, edittype: "select",
editoptions: {
value: {}
}
}
],
pager: "#jqquotesPager",
viewrecords: true,
caption: "Quotes",
gridview: true,
loadonce: false, //Important - Doesn't work without - might need server side paging?
}).navGrid('#jqquotesPager', { edit: true, add: true, del: true }, // options
{
url: '../WebService1.asmx/modifyDataQuotes',
closeAfterEdit: true,
beforeShowForm: function (form) {
$('#docid', form).attr("disabled", true);
},
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function (postData) {
if (postData.exercise_value === undefined) { postData.exercise_value = null; }
return JSON.stringify(postData);
}
}, // edit options
{
url: "../WebService1.asmx/addDataQuotes",
closeAfterAdd: true,
beforeShowForm: function (form) {
$('#docid', form).attr("disabled", true);
},
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function (postData) {
if (postData.exercise_value === undefined) { postData.exercise_value = null; }
return JSON.stringify(postData);
}
}, // add options
{
url: "../WebService1.asmx/deleteDataQuotes",
ajaxDelOptions: { contentType: "application/json" },
serializeDelData: function (postData) {
if (postData.exercise_value === undefined) { postData.exercise_value = null; }
return JSON.stringify(postData);
}
}, //del options
{
multipleSearch: true,
recreateFilter: true,
closeOnEscape: true,
overlay: false
}, // search options
);
}
Code for Datepicker
//Define Datepicker
$grid = $("#jqquotes"),
initDateEdit = function (elem) {
$(elem).datepicker({
dateFormat: "dd-mm-yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
},
initDateSearch = function (elem) {
var $self = $(this);
setTimeout(function () {
$(elem).datepicker({
dateFormat: "dd-mm-yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showWeek: true,
showButtonPanel: true,
onSelect: function () {
if (this.id.substr(0, 3) === "gs_") {
// call triggerToolbar only in case of searching toolbar
setTimeout(function () {
$self[0].triggerToolbar();
}, 100);
}
}
});
}, 100);
},
numberTemplate = {
formatter: "number", align: "right", sorttype: "number",
editrules: { number: true, required: true },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge", "nu", "nn", "in", "ni"] }
};
I have spent about half a day on this, but cannot for the life of me figure out whats happening.
Any help greatly appreciated.
There is a not correct setting in the srcformat and the actual format that come from the data source. By definition the ISO8601Long is described like :
ISO8601Long:"Y-m-d H:i:s",
See here
Your source data format is d/m/Y H:i:s, which is quite different. In order this to worku set it like this:
...
{
name: 'quote_date', formatter: 'date', datefmt: "d-m-Y", editoptions: { dataInit: initDateEdit },
formatoptions: { srcformat: "d/m/Y H:i:s", newformat: "d-m-Y" }, index: 'quote_date', width: 100, editable: true
},
Note that I have changed the datefmt and newformat in case you want to remove the trailing zero's. This will be compatible with your datepicker settings

jqGrid enable navigation bar save icon on ondblClickRow event

I have set the jqGrid row edit on ondblClickRow event. once a row is double clicked I want to enable save icon on navigation bar. How can I do that.
ondblClickRow: function (rowid) {
jQuery(this).jqGrid('editRow', rowid, true, null, null);
},
Please help
thanks
jQuery(document).ready(function ($) {
grid = $("#SupplementsGrid");
getColumnIndexByName = function (grid, columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), i = 0, l = cm.length;
for (; i < l; i += 1) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
};
var DataEditUrl = baseSiteURL + 'HotelSupplements/Edit';
var DataAddUrl = baseSiteURL + 'HotelSupplements/Create';
var lastSel;
grid.jqGrid({
url: gridDataUrl,
editurl: DataEditUrl,
mtype: 'POST',
datatype: 'local',
colNames: ['StartDate', 'EndDate', 'Man', 'RoomType', 'SuppType', 'Supplement', 'BuyRate', 'Val', 'ChargeBy', 'ChargeOn', 'Status', 'DaysOfTheWeek', 'HotelSupplementID'],
colModel: [
{
name: 'StartDate', index: 'StartDate',
resizable: true, formatter: 'date', editoptions: { dataInit: function (elem) { $(elem).datepicker({ minDate: 0 }); } }, editable: true, formatoptions: { newformat: 'm/d/Y' }, width: 125, align: 'left',
editrules: { custom: true, custom_func: function (value, colname) { return validateTwoDates('StartDate', 'EndDate', grid.jqGrid('getGridParam', 'selrow')) } }
},
{ name: 'EndDate', index: 'EndDate', formatter: 'date', editoptions: { dataInit: function (elem) { $(elem).datepicker({ minDate: 0 }); } }, editable: true, formatoptions: { newformat: 'm/d/Y' }, width: 100, align: 'left' },
{ name: 'Mandatory', index: 'Mandatory', editable: true, width: 45, align: 'center', edittype: "checkbox", editoptions: { value: "true:false" } },
{
name: 'RoomTypes', index: 'RoomTypes', width: 300, editable: true, edittype: 'select',
editoptions: {
value: roomTypesFormatterEdit,
custom_element: function (value, options) {
return $.jgrid.createEl.call(this, "select",
$.extend(true, {}, options, { custom_element: null, custom_value: null }),
value);
},
custom_value: function ($elem, operation, value) {
if (operation === "get") {
return $elem.val();
}
},
multiple: true
},
align: 'left', formatter: roomTypesFormatter
},
{
name: 'SupplementTypeID', index: 'SupplementTypeID', width: 115, align: 'left', formatter: supplementTypesFormatter, editable: true, edittype: 'select',
editoptions: {
value: supplementTypesFormatterEdit,
dataEvents: [
{
type: 'change', // keydown
fn: function (e) {
suppTId = $("#" + this.id).val();
myValue = '';
filterSupplementsByTypeID(suppTId);
//grid.jqGrid('setColProp', 'SupplementID', { editoptions: { value: supplementsFormatterEdit} });
var row = $(e.target).closest('tr.jqgrow');
var rowId = row.attr('id');
for (k = 0; k < filteredSupplements.length; k++) {
myValue += '<option value=' + filteredSupplements[k].SupplementID + '>' + filteredSupplements[k].Name + '</option>';
}
$("select#" + rowId + "_SupplementID", row[0]).html(myValue);
}
}
]
}
},
{
name: 'SupplementID', index: 'SupplementID', width: 120, align: 'left', formatter: supplementsFormatter, editable: true, edittype: 'select',
editoptions: {
value: supplementsFormatterEdit
}
},
{ name: 'BuyRate', index: 'BuyRate', editable: true, width: 90, align: 'left', sorttype: 'int', editrules: { custom: true, custom_func: validNum } },
{
name: 'ChargeValueTypeID', index: 'ChargeValueTypeID', width: 70, align: 'left', formatter: ChargeValueTypesFormatter, editable: true, edittype: 'select',
editoptions: {
value: chargeValueTypesFormatterEdit
}
},
{
name: 'ChargeByTypeID', index: 'ChargeByTypeID', width: 100, align: 'left', formatter: ChargeByTypesFormatter, editable: true, edittype: 'select',
editoptions: {
value: chargeByTypesFormatterEdit
}
},
{
name: 'ChargeOnTypeID', index: 'ChargeOnTypeID', width: 100, align: 'left', formatter: ChargeOnTypesFormatter, editable: true, edittype: 'select',
editoptions: {
value: chargeOnTypesFormatterEdit
}
},
{ name: 'Active', index: 'Active', width: 60, align: 'left', editable: true, edittype: "checkbox", editoptions: { value: "true:false" } },
{
name: 'DaysOfTheWeek', index: 'DaysOfTheWeek', width: 250, align: 'left', editable: true, edittype: 'select', formatter: function (cellvalue, options, rowObject) {
output = '';
if (rowObject.MonValid) {
output += 'Monday,';
} if (rowObject.TueValid) {
output += 'Tuesday,';
} if (rowObject.WedValid) {
output += 'Wednesday,';
} if (rowObject.ThuValid) {
output += 'Thursday,';
} if (rowObject.FriValid) {
output += 'Friday,';
} if (rowObject.SatValid) {
output += 'Saturday,';
} if (rowObject.SunValid) {
output += 'Sunday,';
}
output = output.substring(0, output.length - 1);
if (output != '') {
return output;
} else {
return cellvalue;
}
}, editoptions: {
value: 'Monday:Monday;Tuesday:Tuesday;Wednesday:Wednesday;Thursday:Thursday;Friday:Friday;Saturday:Saturday;Sunday:Sunday',
custom_element: function (value, options) {
return $.jgrid.createEl.call(this, "select",
$.extend(true, {}, options, { custom_element: null, custom_value: null }),
value);
},
custom_value: function ($elem, operation, value) {
if (operation === "get") {
return $elem.val();
}
},
multiple: true
}
},
{
name: 'HotelSupplementID',
index: 'HotelSupplementID',
width: 25, editable: true,
editrules: {
//required: true,
edithidden: true
}, hidden: true,
editoptions: {
dataInit: function (element) {
//jq(element).attr("readonly", "readonly");
}
}
}
],
jsonReader: {
root: 'Rows',
page: 'Page',
total: 'Total',
records: 'Records',
repeatitems: false,
id: "12",
},
subGrid: true,
subGridRowExpanded: function (subgrid_id, row_id) {
var subgrid_table_id;
subgrid_table_id = subgrid_id + "_t";
jQuery("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table>");
jQuery("#" + subgrid_table_id).jqGrid({
url: supplementChildRateurl + '?id=' + row_id,
datatype: "json",
colNames: ['MinAge', 'MaxAge', 'BuyRate', ],
colModel: [
{ name: "MinAge", index: "MinAge", width: 130 },
{ name: "MaxAge", index: "MaxAge", width: 130 },
{ name: "BuyRate", index: "BuyRate", width: 130 }
],
height: '100%',
rowNum: 20,
});
},
ondblClickRow: function (rowid) {
jQuery(this).jqGrid('editRow', rowid, true, null, null);
},
onSelectRow: function (id) {
if (id && id !== lastSel) {
jQuery(this).restoreRow(lastSel);
lastSel = id;
}
},
resizeStop: function (newwidth, index) {
jQuery(this.bDiv).find('>div:first>table.ui-jqgrid-btable:first')
.jqGrid('setGridWidth', newwidth);
},
paging: true,
loadonce: true,
loadComplete: function (data) {
var iCol = getColumnIndexByName(grid, 'act');
jQuery("#SupplementsGrid").children("tbody")
.children("tr.jqgrow")
.children("td:nth-child(" + (iCol + 1) + ")")
.each(function () {
$("<div>",
{
title: "Custom",
mouseover: function () {
$(this).addClass('ui-state-hover');
},
mouseout: function () {
$(this).removeClass('ui-state-hover');
},
click: function (e) {
}
}
).css({ "margin-left": "5px", float: "left" })
.addClass("ui-pg-div ui-inline-custom")
.append('<span class="ui-icon ui-icon-document"></span>')
.appendTo($(this).children("div"));
});
jQuery("#SupplementsGrid").trigger("reloadGrid");
jQuery("#SuccessMsg").html("");
//$("#SupplementsGrid").jqGrid('setGridParam',{datatype:'local'});
var rowIds = $("#SupplementsGrid").jqGrid('getDataIDs');
$.each(rowIds, function (i, row) {
var rowData = $("#SupplementsGrid").getRowData(row);
if (rowData.InputType == 'select') {
}
});
},
gridview: true,
rowNum: 20,
rowList: [5, 10, 20, 50, 100],
pager: jQuery('#pager'),
emptyrecords: "Nothing to display",
sortable: true,
sortname: 'StartDate',
sortorder: "desc",
viewrecords: true,
height: 'auto',
width: 1068,
caption: "Supplements",
});
$('#SupplementsGrid').jqGrid('navGrid', '#pager',
{
edit: false,
add: false,
del: false,
search: false
},
//edit options
{ url: DataEditUrl },
//add options
{ url: DataAddUrl },
//delete options
{ url: '/home1/DeleteUserData' }
);
parameters = {
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon: "ui-icon-plus",
save: true,
saveicon: "ui-icon-disk",
cancel: true,
cancelicon: "ui-icon-cancel",
editParams: {
keys: false,
oneditfunc: null,
successfunc: function (val) {
if (val.responseText != "") {
// alert(val.responseText);
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
},
url: null,
extraparam: {
EmpId: function () {
var sel_id = $('#SupplementsGrid').jqGrid('getGridParam', 'selrow');
var value = $('#SupplementsGrid').jqGrid('getCell', sel_id, '_id');
return value;
}
},
aftersavefunc: null,
errorfunc: null,
afterrestorefunc: null,
restoreAfterError: true,
mtype: "POST"
},
addParams: {
useDefValues: true,
addRowParams: {
keys: true,
extraparam: {},
// oneditfunc: function () { alert(); },
successfunc: function (val) {
if (val.responseText != "") {
//alert(val.responseText);
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
}
}
}
}
jQuery("#SupplementsGrid").jqGrid('inlineNav', '#pager', parameters);
});
You don't posted details of your implementation, but I can suppose that you use inlineNav method. inlineNav uses simple rule for generating the value of id attribute of all navigator icons. The ids of all inline editing buttons are set based on the id of the grid and a suffix: "_iladd", "_iledit", "_ilsave", "_ilcancel". For example is the grid have id="list" then the id of Save button will be "list_ilsave". If required you can disable any button by addressing it by its id (for example $("#list_ilsave").removeClass('ui-state-disabled'); - enable Save button and $("#list_ilsave").addClass('ui-state-disabled'); - disable it). You can use aftersavefunc and afterrestorefunc options of editRow to change the state of navigator buttons after saving or discarding of changes. In the same way you can use jQuery.click to simulate click on any button. For example $("#list_ilsave").click(); will simulate clicking on the Save button.

Categories