Related
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>
guys i am using jqgrid ... i want to get id of the row upon clicking on the image only without selecting the whole row first .. here is my code
<script type="text/javascript">
$(document).ready(function() {
$("#jqGrid").jqGrid({
url: 'data.json',
datatype: "json",
styleUI: "Bootstrap",
colModel: [{
label: 'Order ID',
name: 'OrderID',
key: true,
width: 75,
hidden: true
}, {
label: 'From Date',
name: 'FromDate',
width: 150,
editable: true,
edittype: "text",
id: "ui-datepicker-div",
editoptions: {
dataInit: function(element) {
$(element).datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
orientation: 'auto bottom'
});
},
},
}, {
label: 'To Date',
name: 'ToDate',
width: 150,
editable: true,
edittype: "text",
editoptions: {
dataInit: function(element) {
$(element).datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
orientation: 'auto bottom'
});
},
},
}, {
label: 'Customer ID',
name: 'CustomerID',
width: 150
}, {
label: 'Ship Name',
name: 'ShipName',
width: 200
}, {
label: 'Row Data',
name: 'RowData',
align: 'center',
formatter: function() {
return "<img src='resources/icon.jpg' onclick='OpenDialog()' alt='Data Row' />";
width = 15;
}
}, ],
loadonce: true,
......
});
});
...........
function OpenDialog() {
var result = "";
var grid = $("#jqGrid");
var rowKey = grid.getGridParam("selrow");
rowData = grid.getLocalRow(rowKey);
for (var item in rowData) {
if (item == 'RowData') {
break;
}
result += rowData[item] + ', ';
}
alert(result);
}
any help please how to get id of row upon only clicking on the image ??.. thanks a lot .. thanks in advance
use this html:
onclick='OpenDialog(this)'
and in OpenDialog use closest jquery method:
function OpenDialog(element) {
var id = $(element).closest('tr').attr('id');
...
}
In my jqGrid there are 4 select in which two is working fine and two is not working.
Issue :
When I use the below snippet :
var stagevalues = GetStagesValues();
var salesvalues = GetSalesValues();
var owners = GetDataOwnershipValues();
xmlstring = Stages; //.XmlToString();
$("#uxStages").jqGrid({
datatype: 'xmlstring',
datastr: xmlstring,
mtype: 'GET',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
xmlReader: { repeatitems: false, root: "BO>SalesOpportunitiesLines", row: 'row' },
colNames: ['LineNum', 'Star Date', 'Close Date', 'Sales Employee', 'Stage', 'Percentage', 'Potential Amount', 'Document Type', 'Doc. No.', 'Owner'],
colModel: [
{ name: 'LineNum', key: true, index: 'LineNum', hidden: false, sortable: false, width: 60 },
{ name: 'StartDate', key: false, index: 'StartDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'Ymd', newformat: 'd-M-y' },
formatter: function (cellValue, opts, rawdata, action) {
if (action === "edit") {
// input data have format "dd-mm-yy" format - "20-03-2015"
var input = cellValue.split("-");
if (input.length === 3) {
return input[0] + "-" + input[1] + "-" + input[2];
}
} else if (cellValue.length === 8) {
// input data have format "yymmdd" format - "20150320"
var year = cellValue.substr(0, 4), month = cellValue.substr(4, 2), day = cellValue.substr(6, 2);
return day + "-" + month + "-" + year;
}
return cellValue; // for empty input for example
},
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-y' });
}
}
},
{ name: 'ClosingDate', key: false, index: 'ClosingDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'Ymd', newformat: 'd-m-Y' },
formatter: function (cellValue, opts, rawdata, action) {
if (action === "edit") {
// input data have format "dd-mm-yy" format - "20-03-2015"
var input = cellValue.split("-");
if (input.length === 3) {
return input[0] + "-" + input[1] + "-" + input[2];
}
} else if (cellValue.length === 8) {
// input data have format "yymmdd" format - "20150320"
var year = cellValue.substr(0, 4), month = cellValue.substr(4, 2), day = cellValue.substr(6, 2);
return day + "-" + month + "-" + year;
}
return cellValue; // for empty input for example
},
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'SalesPerson', key: false, index: 'SalesPerson', sortable: false, width: 80,
editable: true,
edittype: "select"
},
{ name: 'StageKey', key: false, index: 'StageKey', hidden: false, sortable: false, width: 80,
editable: true,
edittype: "select"
},
{ name: 'PercentageRate', key: false, index: 'PercentageRate', sortable: false, width: 60 },
{ name: 'MaxLocalTotal', key: false, index: 'MaxLocalTotal', sortable: false, width: 100,
editable: true,
edittype: "text",
formatter: 'currency',
formatoptions: { thousandsSeparator: ',' }
},
{ name: 'DocumentType', key: false, index: 'DocumentType', sortable: false, width: 90,
editable: true,
edittype: 'select',
formatter: 'select',
editoptions: {value: "bodt_MinusOne:;bodt_Quotation:Sales Quotations;bodt_Order:Sales Orders;bodt_DeliveryNote:Deliveries;bodt_Invoice:A/R Invoice"
}
},
{ name: 'DocumentNumber', key: false, index: 'DocumentNumber', sortable: false, width: 40 },
{ name: 'DataOwnershipfield', key: false, index: 'DataOwnershipfield', hidden: false, sortable: false, width: 60,
editable: true,
edittype: "select",
unformat: function (cellValue, opts, rawdata, action) {
$('#uxOwner').each(function () {
$('option', this).each(function () {
// if (opts.rowId == 4)
// debugger;
var code = $(this).val();
var name = $(this).text();
if (name == cellValue)
return code;
});
});
}
}
],
rowNum: 100,
viewrecords: true,
gridview: true,
rownumbers: true,
height: 150,
loadonce: true,
width: 1120,
scrollOffset: 0,
ondblClickRow: function (rowid) {
var grid = $("#uxStages");
var selectedRowId = grid.jqGrid('getGridParam', 'selrow');
lastSelection = selectedRowId;
grid.jqGrid('editRow', selectedRowId, true, null, null, null, null, OnSuccessEdit_Stages);
$('#' + selectedRowId + "_StageKey").css('width', '100%');
$('#' + selectedRowId + "_SalesPerson").css('width', '100%');
$('#' + selectedRowId + "_DataOwnershipfield").css('width', '100%');
$('#' + selectedRowId + "_DocumentType").css('width', '100%');
},
loadComplete: function () {
var ids = $("#uxStages").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
if (i < ids.length) {
$("#uxStages").jqGrid('editRow', id);
$("#uxStages").setColProp('SalesPerson', { edittype: "select", editoptions: { value: salesvalues} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('StageKey', { edittype: "select", editoptions: { value: stagevalues} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('DataOwnershipfield', { edittype: "select", editoptions: { value: owners} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").saveRow(id);
}
}
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
if (i < ids.length - 1) {
// $('#' + $.jgrid.jqID(id)).addClass('not-editable-row');
// $('#' + $.jgrid.jqID(id)).addClass('ui-state-error');
}
}
},
onSelectRow: function (id) {
if (id && id !== lastSelection) {
var grid = $("#uxStages");
$('#uxStages').saveRow(lastSelection);
}
}
}).jqGrid('navGrid', { edit: true, edit: true, add: true, del: true, searchOnEnter: false, search: false }, {}, {}, {}, { multipleSearch: false }).trigger('reloadGrid');
function OnSuccessEdit_Stages(id, response, options) {
var LineNum = $('#uxStages').jqGrid('getCell', id, 'LineNum');
var StartDate = $('#uxStages').jqGrid('getCell', id, 'StartDate');
var ClosingDate = $('#uxStages').jqGrid('getCell', id, 'ClosingDate');
var SalesPerson = $('#uxStages').jqGrid('getCell', id, 'SalesPerson'); //getting text part of select and expected to get value
var StageKey = $('#uxStages').jqGrid('getCell', id, 'StageKey'); //getting text part of select and expected to get value
var PercentageRate = $('#uxStages').jqGrid('getCell', id, 'PercentageRate');
var MaxLocalTotal = $('#uxStages').jqGrid('getCell', id, 'MaxLocalTotal');
var DocumentType = $('#uxStages').jqGrid('getCell', id, 'DocumentType'); //getting value which is correct
var DocumentNumber = $('#uxStages').jqGrid('getCell', id, 'DocumentNumber');
var DataOwnershipfield = $('#uxStages').jqGrid('getCell', id, 'DataOwnershipfield'); //getting value which is correct
$oppor.find('Response Data BOM BO SalesOpportunitiesLines row').each(function (index) {
if ($(this).find('LineNum').text() == LineNum) {
if (LineNum == 4)
// $(this).find('StartDate').text(StartDate);
// $(this).find('ClosingDate').text(ClosingDate);
$(this).find('SalesPerson').text(SalesPerson);
$(this).find('StageKey').text(StageKey);
$(this).find('PercentageRate').text(PercentageRate);
$(this).find('MaxLocalTotal').text(MaxLocalTotal);
$(this).find('DocumentType').text(DocumentType);
$(this).find('DocumentNumber').text(DocumentNumber);
$(this).find('DataOwnershipfield').text(DataOwnershipfield);
}
});
return true;
}
I am getting text part in first 2 select instead of value where as in the last 2 select it gives me value instead of text which is expected.
I use unformat function also to get the value part, But doesn't work.
I want somebody to point me the issue, I don't know how to deal with such issues.
Thanks in anticipation.
The reason of the problem could be the wrong order of calls editRow and setColProp in the for-loop inside of loadComplete. If you need to change editoptions.value, which will be used during editing, you should use it before the editing will be started. Thus setColProp should be called before editRow.
The call of saveRow directly after call of editRow seems me very suspected. You set salesvalues, stagevalues and owners before you crated the grid (see the lines var salesvalues = GetSalesValues(); and other). So it seems that you can use
{ name: 'SalesPerson', width: 80, editable: true, edittype: "select",
editoptions: { value: salesvalues} }
directly in colModel. No loop inside of loadComplete seems be required.
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.
I'm attempting to make entire rows in jTable clickable so that they reveal their respective child tables. I found a lovely snippet of code by Jules Colles (here) for click events on rows, but I'm unsure how to integrate the openChildTable method with it. My attempted code is as follows:
<div id="UsernameTable"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#UsernameTable').jtable({
title: 'Username Table',
paging: true,
sorting: true,
defaultSorting: 'Name ASC',
openChildAsAccordion: true,
actions: {
listAction: 'doStuff.php?action=list'
},
fields: {
ID: {
key: true,
create: false,
edit: false,
list: false
}
Name: {
title: 'Name',
width: '25%'
},
Comment: {
title: 'Comment',
width: '50%'
},
Date: {
title: 'Date',
width: '25%',
type: 'date',
create: false,
edit: false
}
},
recordsLoaded: function(event, userData) {
$('.jtable-data-row').click(function() {
var row_id = $(this).attr('data-record-key');
//alert('clicked row with id '+row_id);
$('#UsernameTable').jtable('openChildTable', row_id, {
actions: {
listAction: 'doStuff.php?action=listChild&ID=' + userData.record.ID
},
fields: {
ID: {
type: 'hidden',
defaultValue: userData.record.ID
},
SecondKey: {
key: true,
create: false,
edit: false,
list: false
},
DOB: {
title: userData.record.Name + '\'s Date of Birth',
width: '25%',
type: 'date'
},
Hometown: {
title: 'Hometown',
width: '50%',
type: 'textarea'
},
Age: {
title: 'Age',
width: '25%'
}
}
}, function (data) {
data.childTable.jtable('load');
});
});
}
});
});
</script>
I've independently tested everything else so I know the PHP and MySQL is all working properly. I've also verified things are functional with the traditional route of using display: to add a column and use a toggle button to display the children. But, again, I really want to be able to click anywhere on a row and have it unfurl a new table. Any help would be greatly appreciated.
You have to add the selecting options to main table (selecting: true,) and use the selectionChanged function. Inside this callback you can use the 'selectedRows' to open childs (is easier if multipleselect is not active)
selectionChanged: function () {
$selectedRows.each(function () {
// Open child stuff
});
},
hope it's usefull for you
/**
* Document JTable Data source
*
* #author pradeep.mishra
* #version 1.0
* #date May 20, 2015
*/
$(document).ready(function() {
$(document)
.ajaxStart($.blockUI({
message: ''
}))
.ajaxStop($.unblockUI); // Blocks UI till Ajax Call
// finishes working.
var baseURL = getBaseUrl();
var globalRecords = [];
// setup the jTable that will display the results
$('#documentSearchDiv').jtable({
title: 'Document',
paging: false,
pageSize: 30,
sorting: false,
pageSizeChangeArea: false,
selecting: true,
multiselect: false,
selectingCheckboxes: false,
columnResizable: false,
columnSelectable: false,
loadingAnimationDelay: 2000,
dialogShowEffect: 'scale',
dialogHideEffect: 'scale',
actions: {
listAction: baseURL + '/document/search',
updateAction: baseURL + '/document/update',
deleteAction: baseURL + '/document/remove',
},
fields: {
id: {
key: true,
create: false,
edit: false,
list: false
},
// CHILD TABLE DEFINITION FOR
// "Document Relationship"
DocumentRelationship: {
title: '',
width: '5%',
sorting: true,
edit: false,
create: false,
display: function(data) {
// Create an image that will
// be used to open child
// table
var $img = $('<img src="' + baseURL + '/static/css/themes/metro/ThemedExpand.png" title="Modify Code and Value" />');
// Open child table when
// user clicks the image
$img.click(function() {
var check = $img.attr('src');
if (check == baseURL + '/static/css/themes/metro/ThemedExpand.png') {
$img.attr('src', '' + baseURL + '/static/css/themes/metro/ThemedCollap.png');
$('#documentSearchDiv')
.jtable('openChildTable',
$img.closest('tr'), {
title: 'please enter your information',
selecting: true,
actions: {
listAction: function(postData, jtParams) {
return {
"Result": "OK",
"Records": data.record.relationships,
"TotalRecordCount": 2
};
},
updateAction: function(data) {
var docData = JSON.parse(jTableSelect('documentSearchDiv'));
var docRelData = postStringToJson(data);
docRelData = JSON.parse(docRelData);
var id = docData[0].id;
var document = {};
document.id = id;
docRelData.document = document;
return $.Deferred(function($dfd) {
function success(data) {
$dfd.resolve(data);
}
function failure() {
$dfd.reject();
}
post(baseURL + '/documentRelationship/update', 'POST', JSON
.stringify(docRelData), success, failure);
});
},
deleteAction: baseURL + '/documentRelationship/remove',
},
fields: {
id: {
key: true,
create: false,
edit: false,
list: false
},
relationshipCode: {
title: 'Code',
width: '15%',
inputClass: 'validate[required]',
},
relationshipValue: {
title: 'Value',
width: '15%',
inputClass: 'validate[required]',
},
},
formCreated: function(event, data) {
data.form.validationEngine('attach', {
binded: false
});
},
// Validate
// inner
// form
// when
// it
// is
// being
// submitted
formSubmitting: function(event, data) {
return data.form.validationEngine('validate');
},
// Dispose
// validation
// logic
// when
// form
// is
// closed
formClosed: function(event, data) {
data.form.validationEngine('hide');
data.form.validationEngine('detach');
},
loadingRecords: function() {
$('.jtable-child-table-container div.jtable-main-container table.jtable thead').html(
'<tr><th class="jtable-column-header" style="width: 15%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Code</span><div class="jtable-column-resize-handler"></div></div></th><th class="jtable-column-header" style="width: 15%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Value</span></div></th><th class="jtable-command-column-header" style="width: 1%;" colspan="2"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Action</span></div></th></tr>')
}
},
function(data) {
data.childTable.jtable('load');
});
} else {
$('#documentSearchDiv')
.jtable('closeChildTable', $img.closest('tr'));
$img.attr('src', '' + baseURL + '/static/css/themes/metro/ThemedExpand.png');
}
});
return $img;
}
},
fileName: {
title: 'File Name',
width: '15%',
inputClass: 'validate[required]',
},
description: {
title: 'Description',
width: '30%',
inputClass: 'validate[required]',
},
type: {
title: 'Document Type',
width: '15%',
inputClass: 'validate[required]',
},
mimeType: {
title: 'MIME Type',
width: '15%',
inputClass: 'validate[required]',
},
},
// Initialize validation logic when a
// form is created
formCreated: function(event, data) {
data.form.validationEngine('attach', {
binded: false
});
},
// Validate form when it is being
// submitted
formSubmitting: function(event, data) {
return data.form.validationEngine('validate');
},
// Dispose validation logic when form is
// closed
formClosed: function(event, data) {
data.form.validationEngine('hide');
data.form.validationEngine('detach');
},
recordsLoaded: function(event, data) {
var headers = JSON.parse('{"0": { "sorter": "text" },"1" : {"sorter" : "text" },"2": {"sorter" : "text"},"3": {"sorter" : "text"}}');
initializeTableSorter(headers);
},
loadingRecords: function() {
$('.jtable-main-container table.jtable thead').html(
'<tr><th class="jtable-column-header" style="width: 2%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text"></span></div></th><th class="jtable-column-header" style="width: 18.3686%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">File Name</span></div></th><th class="jtable-column-header" style="width: 36.7372%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Description</span></div></th><th class="jtable-column-header" style="width: 18.3686%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Document Type</span></div></th><th class="jtable-column-header" style="width: 18.3686%;"><div class="jtable-column-header-container"><span class="jtable-column-header-text">MIME Type</span></div></th><th class="jtable-command-column-header" style="width: 1%;" colspan="2"><div class="jtable-column-header-container"><span class="jtable-column-header-text">Action</span></div></th></tr>')
$('.jtable').addClass("tablesorter");
}
});
$('#documentSearchDiv').jtable('load');
$('#documentSearchInnerDiv') jtable({
title: 'Document Relationship',
paging: false,
pageSize: 30,
sorting: false,
clientOnly: true,
useBootstrap: true,
editinline: {
enable: true
},
pageSizeChangeArea: false,
selecting: true,
multiselect: false,
selectingCheckboxes: false,
columnResizable: false,
columnSelectable: false,
loadingAnimationDelay: 2000,
dialogShowEffect: 'scale',
dialogHideEffect: 'scale',
actions: {
createAction: function(data) {
console.info(postStringToJson(data));
var dat = postStringToJson(data);
return {
"Result": "OK",
"Record": JSON.parse(dat)
};
},
},
fields: {
id: {
type: 'hidden',
},
relationshipCode: {
title: 'Code',
width: '15%',
inputClass: 'validate[required]',
},
relationshipValue: {
title: 'Value',
width: '15%',
inputClass: 'validate[required]',
},
},
// Initialize validation logic when a
// form is created
formCreated: function(event, data) {
data.form.validationEngine('attach', {
binded: false
});
},
// Validate form when it is being
// submitted
formSubmitting: function(event, data) {
return data.form.validationEngine('validate');
},
// Dispose validation logic when form is
// closed
formClosed: function(event, data) {
data.form.validationEngine('hide');
data.form.validationEngine('detach');
},
recordAdded: function(event, data) {
globalRecords.push(data.record);
}
});
$("#documentAddNew")
.submit(function(e) {
e.preventDefault();
var data = form2js('documentAddNew', '.', false);
data.relationships = globalRecords;
return $.Deferred(function($dfd) {
function success() {
$("#documentSearchInnerDiv tr")
.remove();
globalRecords = [];
$('#documentModal')
.modal('hide');
$('#documentSearchDiv')
.jtable('reload');
}
function failure() {
$dfd.reject();
}
post(baseURL + '/document/save', "POST", JSON.stringify(data), success, failure);
$("#documentAddNew")[0].reset();
});
});
});