I'm using an web method to get an json response, but the Refresh button in the grid doesn't work.
This is the code Behind:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getData()
{
string data = GetJson();
return data;
}
public static string GetJson()
{
List<NameData> dataList = new List<NameData>();
NameData data1 = new NameData();
data1.pkNameID = 1;
data1.Name = "Name_One";
dataList.Add(data1);
NameData data2 = new NameData();
data2.pkNameID = 2;
data2.Name = "Name_two";
dataList.Add(data2);
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(dataList);
}
public class NameData
{
public int pkNameID { get; set; }
public string Name { get; set; }
}
And this is the ajax script:
$(document).ready(function () {
GetData();
});
function GetData() {
$.ajax({
type: "POST",
url: "ListTest.aspx/getData",
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: false,
success: function (response) {
var item = $.parseJSON(response.d);
if (item != null && item != "" && typeof (item) != 'undefined') {
$("#list").jqGrid({
url: 'ListTest.aspx/getData',
data: item,
datatype: 'local',
colNames: ['pkNameID', 'Name'],
colModel: [
{ name: 'pkNameID', index: 'pkNameID', width: 30, align: 'left', stype: 'text', editable: false },
{ name: 'Name', index: 'Name', width: 80, align: 'left', stype: 'text', editable: true }],
rowNum: 5,
rowList: [10, 20, 30],
pager: '#pager',
sortname: 'pkNameID',
sortorder: 'desc',
caption: "Test Grid",
viewrecords: true,
async: false,
loadonce: false,
gridview: true,
width: 500,
edit: true,
loadComplete: function (result) {
//alert(jQuery("#list").jqGrid('getGridParam', 'records'));
},
loadError: function (xhr) {
alert("The Status code:" + xhr.status + " Message:" + xhr.statusText);//Getting reponse 200 ok
}
}).navGrid('#pager', { edit: true, add: false, del: false, search: false, refresh: true });
}
else {
var result = '<tr align="left"><td>' + "No Record" + '</td></tr>';
$('#list').empty().append(result);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
}
So, When i try to click in the refresh button(I need a Server Refresh), the grid doesn't refresh. I try change the datatype: 'local' to datatype: 'json' but this get error code: 200. I don't know how to fix it.
Thanks for you future help!
I think it doesn't work because you create the table inside the "success" of the ajax call.
I'd suggest either to add a custom refresh button that calls the getData function (add $("#list").GridUnload() at the beginning of the function) or to make the ajax call inside the jqgrid instantiation.
The first way should be easier, although less elegant.
Following an example for the second solution without the refresh button, but it should be easy to add it to this code:
$("#resTable").jqGrid({
datatype: "json",
mtype: 'POST',
url: "../WS/myServices.asmx/GetData",
postData: "{firstParam:" + JSON.stringify(firstParam) +
", secondParam:" + JSON.stringify(secondParam) +
", thirdParam:" + JSON.stringify(thirdParam) + "}",
loadonce: true,
jsonReader: {
repeatitems: false,
root: function (data) {
if (data && data.d.length > 0) {
return data.d;
}
else
alert("No result");
}
},
ajaxGridOptions: {
contentType: "application/json",
type: 'post',
error: function (result) {
alert(result.responseText);
}
},
colModel: [
{ label: 'Action', name: 'act', width: 100, sortable: false },
{ label: 'Col1', name: 'Col1', width: 250, sortable: false, key: true },
{ label: 'Col2', name: 'Col2', width: 350, sortable: true },
{ label: 'Col3', name: 'Col3', width: 120, sortable: false },
{ label: 'Col4', name: 'Col4', width: 120, sortable: false, hidden:true }
],
height: 'auto',
loadComplete: function () {
var ids = jQuery("#resTable").jqGrid('getDataIDs'); //get the row IDs
for (var i = 0; i < ids.length; i++) {
var funct = "javascript:someFunction('" + ids[i] + "');";
be = '<input type="button" class = "Btn" value="Do something" onclick="' + funct + '" />';
jQuery("#resTable").jqGrid('setRowData', ids[i], { act: be });
}
},
beforeSelectRow: function (rowid, e) {
return false; //to avoid selecting
},
hoverrows: false, //to avoid hovering
caption: "My table"
});
Related
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
I'm using free-jqgrid. i have a nested jqgrid inside another jqgrid (i.e subgrid) with multi-select. I have grouped the parent grid and the grouping works fine. However, when i set the groupCollapse: true, the subgrids remain expanded. Please see the code i have attached and let me know whats missing.
expanded view
group collapsed but subgrid still shows
Function to load parent grid (with grouping)
function LoadActivities() {
if (typeof (showRPMLogFrame) != 'undefined' && showRPMLogFrame.toLowerCase() == true.toString().toLowerCase()) {
//create custom object to bind to jqgrid
var arrNewActivities = [];
var clusterId;
var cluster;
var actId;
var actDesc;
var isCustomActivity;
$("select[id*='drpCluster'] option:not(:first)").each(function () {
clusterId = $(this).val();
cluster = $(this).text();
GetSelectedClusterId($(this).text());
var arrActivities = [];
//get the json data for activities
$.ajax
({
type: "POST",
url: 'url',
cache: false,
async: false,
data: '{"appealId" : "' + appealId + '", "projectId" :"' + (projectId == "" ? "0" : projectId) + '", "clusterId" : "' + clusterId + '", "rpmClusterId" : "' + selectedClusterId + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr, status) {
arrActivities = arr;
for (i = 0; i < arrActivities.d.length; i++) {
actId = arrActivities.d[i].id;
actDesc = arrActivities.d[i].description;
arrNewActivities.push({
"clusterId": clusterId,
"cluster": cluster,
"id": actId,
"description": actDesc,
"isCustomActivity": false,
"isSaved": false
});
}
},
error: function (request, status, error) {
alert('Error in fetching RPM cluster mapped to OPS cluster : ' + cluster + '/n ' + error);
return false;
}
});
});
//gets the activities from database
$.ajax({
type: "POST",
url: 'database webmethod url',
cache: false,
async: false,
data: '{"projectId" :"' + (projectId == "" ? "0" : projectId) + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr, status) {
for (i = 0; i < arr.d.length; i++) {
for (j = 0; j < arrNewActivities.length; j++) {
if (arr.d[i].id == arrNewActivities[j].id) {
arrNewActivities[j].isCustomActivity = arr.d[i].IsCustomActivity;
arrNewActivities[j].isSaved = arr.d[i].IsSaved;
}
}
}
},
error: function (request, status, error) {
alert('Error in loading saved activities for : ' + $(this).text() + '/n ' + error);
return false;
}
});
$("input[type='hidden'][id*='hdnSelectedActivities']").val(JSON.stringify(arrNewActivities));
$("#tblGrid").jqGrid('GridUnload');
"use strict";
$("#tblGrid").jqGrid({
mtype: "GET",
datatype: "local",
data: arrNewActivities,
colModel: [
{ label: "Activity Id", name: "id", key: true, hidden: true },
{ label: "Cluster Id", name: "clusterId", hidden: true },
{ label: "Cluster", name: "cluster", hidden:true, width: 50, cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' } },
{
label: "Activity description", name: "description", required: true, editable: true, wrap: true, edittype: 'textarea', editoptions: { size: 300, maxlength: 2000 },
cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' }
}
],
multiselect: true,
width: 700,
shrinktofit: false,
wrap: true,
loadtext: "Loading...",
emptyrecords: "No activities found.",
//editurl: OPSServicePath + "/SaveActivity",
onSelectRow: function (id) {
SaveGrid();
},
subGrid: true, // set the subGrid property to true to show expand buttons for each row
subgridtype: 'local', // set the subgrid type to json
subGridRowExpanded: ShowChildGrid,
// description of the subgrid model
subGridModel: [{
name: ["IndicatorId", "IndicatorTitle", "Cluster Target", "Project Target"],
//width: [50, 500, 200],
align: ["left", "left", "right", "right"],
params: false
}],
pager: "#jqGridPager",
viewrecords: false,
pgtext: "",
pgbuttons: false,
pginput: false,
gridComplete: function () {
//hide select all checkbox in main grid
$("#cb_tblGrid").hide();
var rowIds = $("#tblGrid").getDataIDs();
$.each(rowIds, function (index, rowId) {
var arrActivities = $("#tblGrid").jqGrid("getGridParam", "data");
var activity = $.grep(arrActivities, function (v) {
if (v.id == rowId) {
return v;
}
});
//expand activities that were saved in database
if (activity[0].isSaved == true) {
$("#tblGrid").expandSubGridRow(rowId);
$("#tblGrid").setSelection(rowId, true);
}
});
},
grouping: true,
groupingView: {
groupField: ["cluster"],
groupColumnShow: [false],
groupText: ["<b>{0}</b>"],
groupOrder: ["asc"],
groupSummary: [false],
groupSummaryPos: ['header'],
groupCollapse: true
}
});
$('#tblGrid').inlineNav('#jqGridPager',
// the buttons to appear on the toolbar of the grid
{
view: false,
edit: false,
add: false,
del: false,
save: false,
savetext: 'Save activity',
cancel: true,
editParams: {
keys: true,
},
addParams: {
keys: true
},
});
//hide select all checkbox in main grid
$("#cb_tblGrid").hide();
}
}
Function to load subgrid
function ShowChildGrid(parentRowID, parentRowKey) {
var arrIndicators = [];
//get the json data for activities
$.ajax
({
type: "POST",
url: 'child grid data api url',
data: '{"projectId" : "' + (projectId == "" ? "0" : projectId) + '", "activityId" : "' + parentRowKey + '"}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function (arr, status) {
if (typeof (arr) != 'undefined' && arr.d.length > 0) {
for (i = 0; i <= arr.d.length - 1; i++) {
arrIndicators.push({
"IndicatorId": arr.d[i].IndicatorId,
"IndicatorTitle": arr.d[i].IndicatorTitle,
"Target": arr.d[i].Target,
"ProjectTarget": arr.d[i].ProjectTarget,
"IsCustomIndicator": arr.d[i].IsCustomIndicator,
"IsSaved": arr.d[i].IsSaved
});
}
}
},
error: function (request, status, error) {
alert('Error in fetching RPM indicators mapped to activity : ');
return false;
}
});
var childGridID = parentRowID + "_table";
var childGridPagerID = parentRowID + "_pager";
// send the parent row primary key to the server so that we know which grid to show
var childGridURL = parentRowKey + ".json";
// add a table and pager HTML elements to the parent grid row - we will render the child grid here
$('#' + parentRowID).append('<table id=' + childGridID + '></table><div id=' + childGridPagerID + ' class=scroll></div>');
$("#" + childGridID).jqGrid({
//url: childGridURL,
mtype: "GET",
datatype: "local",
data: arrIndicators,
page: 1,
multiselect: true,
multiboxonly: true,
colModel: [
{ label: 'Indicator ID', name: 'IndicatorId', key: true, hidden: true },
{ label: 'Indicator Title', name: 'IndicatorTitle', shrinkToFit: true, width: 300, editable: true, editrules: { required: true }, wrap: true, cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' } },
{ label: 'Cluster Target', name: 'Target', editable: false, shrinkToFit: true, width: 100, editrules: { required: true }, wrap: true },
{
label: 'Project Target', name: 'ProjectTarget', editable: true, shrinkToFit: true, width: 100, editrules: { required: true }, wrap: true, formatter: function (cellValue, option) {
return '<input type="text" size="7" name="txtProjectTarget" onblur="CheckInput(this.id);" id="txtProjectTarget_' + option.rowId + '" />';
}
}
],
onSelectRow: function (id) {
SaveGrid();
},
loadonce: true,
autowidth: true,
loadtext: "Loading indicators...",
emptyrecords: "No indicators found.",
shrinktofit: true,
height: '100%',
pager: "#" + childGridPagerID,
viewrecords: false,
pgtext: "",
pgbuttons: false,
pginput: false,
beforeSelectRow: function (rowId, e) {
return $(e.target).is("input:checkbox");
},
gridComplete: function () {
//hide select all checkbox in subgrids
$("input[type='checkbox'][id*='cb_tblGrid_']").hide();
var rowIds = $("#" + childGridID).getDataIDs();
$.each(rowIds, function (i, rowId) {
var arrIndicators = $("#" + childGridID).jqGrid("getGridParam", "data");
var indicator = $.grep(arrIndicators, function (v) {
if (v.IndicatorId == rowId) {
return v;
}
});
if (indicator[0].IsSaved == true) {
$("#" + childGridID).setSelection(rowId, true);
$("#txtProjectTarget_" + indicator[0].IndicatorId).val(indicator[0].ProjectTarget)
}
});
}
});
$("#" + childGridID).inlineNav("#" + childGridPagerID,
{
view: false,
edit: false,
add: false,
del: false,
cancel: false,
save: false
});
//hide select all checkbox in subgrids
$("input[type='checkbox'][id*='cb_tblGrid_']").hide();
//get parent row ID only
var parentRow = parentRowID.toString().split("_", 10)[1].toString();
//bind click event to checkboxes inside subgrid
$("#" + childGridID).find($("input[type='checkbox'][id*='jqg_tblGrid_" + parentRow + "_']")).each(function () {
$(this).on("click", "", function () {
//alert($(this).prop("id"));
//check/uncheck the parent row checkbox if child grid checkboxes are checked/unchecked
var parentTr = $("table#tblGrid tr#" + parentRow);
if (typeof (parentTr) != "undefined") {
var isChecked = $(this).prop("checked");
//if current checkbox is checked, check parent row checkbox; if current checkbox is unchecked, do nothing to parent row checkbox
if (isChecked) {
parentTr.find($("input[type='checkbox'][id='jqg_tblGrid_" + parentRow + "']")).prop("checked", isChecked);
var selRowIds = $("#tblGrid").jqGrid("getGridParam", "selarrrow");
if ($.inArray(parentRowKey, selRowIds) == -1 || selRowIds.length == 0) {
$("#tblGrid").setSelection(parentRowKey, true);
}
}
}
});
});
}
I'm attaching the demo as you had asked. Also I'm using free-jqgrid version 4.14.1.
https://drive.google.com/open?id=0BxSYIVU7orSuaE9VM052VlFKSUE
I have looked at some the examples here and incorporated that into my code. and displays the no records found message. but when there is no records found. I am also gettign "Loading" message showing up
How can i fix this?
Also, when there is record returned is it possible to show number of record returned?
Here is my code
console.log(" bmSearchData "+bmSearchData);
var emptyMsgDiv = $('<div>No URLs have been loaded for evaluation.</div>');
var $grid = $(".search-result");
$grid.jqGrid({
url: bmSearchData,
/**url: "/echo/json/", */
mtype: "POST",
// data: mydata,
datatype: "json",
emptyrecords: "0 records found",
postData: {
json: JSON.stringify(mydata)
},
success: function(mydata, textStatus, jqXHR) {
console.log(" data :" +mydata);
console.log(" data :" + bmUSearchData);
},
colModel: [
{ name: 'FullName',label: 'Name', align:'left', width: 115,search: true },
{ name: 'address',label: 'Address', align:'left', width: 85 ,search: false},
{ name: 'city',label: 'City', align:'left', width: 50 ,search: false},
{ name: 'state',label: 'State', align:'left', width: 20 ,search: true},
{ name: 'zip',label: 'Zip', align:'right', width: 25 ,search: false},
// { name: 'lastModifiedDateTime',label: 'Modified Date', align:'right', width: 45 ,search: false},
],
additionalProperties: ["address", "city", "state","zip"],
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowid) {
var item = $(this).jqGrid("getLocalRow", rowid);
$("#" + $.jgrid.jqID(subgridDivId)).html("<div class=\"col-md-1\"><b>Address: </b></div>" + item.address +
"<br/><div class=\"col-md-1\"><b>City: </b></div>" + item.city + "<br><div class=\"col-md-1\"> <b>Zip: </b></div>" + item.zip + "");
},
iconSet: "fontAwesome",
loadonce: true,
rownumbers: true,
cmTemplate: { autoResizable: true, editable: true },
autoResizing: { compact: true },
forceClientSorting: true,
sortname: "Symbol",
//height:"auto",
caption: "<b>Result List</b>",
viewrecords: true,
autowidth: true, // set 'true' here
shrinkToFit: true, // well, it's 'true' by default
loadError: function (jqXHR, textStatus, errorThrown) {
var p = $(this).jqGrid("getGridParam"),
$errorDiv = $(this.grid.eDiv),
$errorSpan = $errorDiv.children(".ui-jqgrid-error");
$errorSpan.html("No Data Available");
$errorDiv.show();
if (p.errorDisplayTimeout) {
setTimeout(function () {
$errorSpan.empty();
$errorDiv.hide();
}, p.errorDisplayTimeout);
}
},
loadComplete: function () {
var count = grid.getGridParam();
var ts = grid[0];
if (ts.p.reccount === 0) {
grid.hide();
emptyMsgDiv.show();
} else {
grid.show();
emptyMsgDiv.hide();
}
}
});
$grid.jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "cn"});
// place div with empty message insde of bdiv
emptyMsgDiv.insertAfter($grid.parent());
$(window).resize(function () {
var outerwidth = $('#grid').width();
$('.search-result').setGridWidth(outerwidth); // setGridWidth method sets a new width to the grid dynamically
});
HTML
<div class="col-md-10 col-sm-10">
<div id="grid" style="margin:10px 0 20px 0">
<table class="search-result" style=""></table>
</div>
</div>
I have two drop down lists, the first one gets populated from the database values and the second one(PriceCode) depends on what the user selects in the first one(CurrCd). My question is how do I populate that second list dynamically? I am trying to do it in dataEvents but have no way of referencing the second drop down list in edit mode. Is there a correct and logical way of doing so?
Here is my code so far:
grid.jqGrid({
datatype: 'local',
jsonReader: als.common.jqgrid.jsonReader('EntityCd'),
mtype: 'POST',
pager: '#billingPager',
loadonce: true,
colNames: ['Currency', 'Status', 'Bill Curr', 'Price Code'],
colModel: [
{
{ name: 'DefaultCurr', index: 'DefaultCurr', width: 20, sortable: false },
{ name: 'BillStatus', index: 'BillStatus', width: 13, sortable: false },
{
name: 'CurrCd', index: 'CurrCd', width: 20, sortable: false,
editable: true,
edittype: 'select', stype: 'select',
editoptions: {
dataUrl: als.common.getServerPath() + 'LegalEntitiesAjax/GetCurrencies',
dataEvents:[{
type:"change",
fn: function (e) {
//populate price code list here
//below does not work to populate PriceCode
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json; charset=utf-8',
url: als.common.getServerPath() + 'LegalEntitiesAjax/GetPriceList',
data: JSON.stringify({ curcd: this.value }),
async: false,
success: function (data) {
for(i=0; i < data.length; i++) {
$('select#PriceCode').append('<option val=\"' + data[i].PriceCode + '">' + data[i].Description + '</option>');
}
},
error: function (val) { }
});
}
}],
buildSelect: function (data) {
var currSelector = $("<select id='selCurr' />");
$(currSelector).append($("<option/>").val('').text('---Select Currency---'));
var currs = JSON.parse(data);
$.each(currs, function () {
var text = this.CurName;
var value = this.CurCode;
$(currSelector).append($("<option />").val(value).text(text));
});
return currSelector;
}
}
},
{ name: 'PriceCode', index: 'PriceCode', width: 20, sortable: false, editable: true, edittype: 'select', stype: 'select'}
],
loadtext: 'Loading...',
caption: "Bill Entities",
scroll: true,
hidegrid: false,
height: 300,
width: 650,
rowNum: 1000,
altRows: true,
altclass: 'gridAltRowClass',
onSelectRow: webview.legalentities.billing.onBillingSelected,
loadComplete: function (data) {
if (data.length > 0)
{
}
var rowIds = $('#billingGrid').jqGrid('getDataIDs');
$("#billingGrid").jqGrid('setSelection', rowIds[0]);
},
rowNum: 1000
});
grid.jqGrid('navGrid', '#billingPager', {
add: ($("#dev").text() == "True" || $("#globalqc").text() == "True"),
edit: false,
del: false,
search: false,
refresh: false
},
{ // Edit Options
},
{ // Add Options
addCaption: 'Add New Billing Entity',
beforeInitData: function (formid) {
},
url: als.common.getServerPath() + 'LegalEntitiesAjax/AddBillingEntity/',
recreateForm: true,
closeAfterAdd: true,
reloadAfterSubmit: true
},
{ // Del Options
});
The old answer shows how one can implement the dependent selects. You use form editing. Thus the <select> element of PriceCode column of the form editing will have the id="PriceCode". You can use $("#PriceCode").html(/*new options*/); to change the options of <select> editing field of PriceCode column inside of change event handler of CurrCd column.
I am using jqGrid for some purpose. In this grid there are 6 columns in which last columns is just integer value (NoLicense-available license count) and last 2nd is checkbox.
I want to make following functionality using this grid.
If checkbox is tick then value of NoLicense must be NoLicense++;
2 if the same checkbox is untick then value of NoLicense must be NoLicense--;
If NoLicense=0 then alert('License exhausted');
Below is my code:
$.ajax({
type: "POST",
url: url,
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
try {
var msg = JSON.parse(xhr.responseText);
$(this).MessageBox('error', msg.Message);
}
catch (e) {
$(this).MessageBox('error', xhr.responseText);
}
return false;
$(this).HideBusy();
},
success: function (data) {
var xmlString = data.d;
if (xmlString != '') {
$("#AvailableLicense").jqGrid({
ajaxGridOptions: { contentType: 'application/xml; charset=utf-8' },
datatype: 'xmlstring',
datastr: xmlString,
xmlReader: { root: "AvailableLicenses", row: "row", repeatitems: false, id: "ItemCode" },
colNames: ['Code', 'Name', 'Profile Name', 'Expires On', 'Used', 'Available'],
colModel: [
{ name: 'ItemCode', index: 'TenantConfID', align: "left", width: 40 },
{ name: 'Itemname', index: 'ObjectTypeID', align: "left", width: 40 },
{ name: 'ProfileName', index: 'CRMObjectTypeID', align: "left", width: 20 },
{ name: 'EndDate', index: 'SAPObjectTypeID', align: "left", width: 40, formatter: 'date', formatoptions: { srcformat: 'Y/m/d', newformat: 'd-m-Y'} },
{ name: 'Used', index: 'Used', align: "center", width: 20, editable: true, edittype: 'checkbox', formatter: 'checkbox',
editoptions: { value: "1:0", readonly: false }
},
{ name: 'U_NoUsers', index: 'SAPObjectText', align: "center", width: 40 }
],
onSelectRow: function (rowid, status, e) {
UserRowID = $("#ClientUsers").jqGrid('getGridParam', 'selrow');
debugger;
if (UserRowID != null) {
selectedRowId = $("#AvailableLicense").jqGrid('getGridParam', 'selrow');
$('#AvailableLicense').jqGrid('editRow', selectedRowId, true);
var $target = $(e.target), $td = $target.closest("td"),
iCol = $.jgrid.getCellIndex($td[0]),
colModel = $(this).jqGrid("getGridParam", "colModel");
if (iCol >= 0 && $target.is(":checkbox")) {
var Count = $("#AvailableLicense").jqGrid('getCell', selectedRowId, 'U_NoUsers');
var Used = $("#AvailableLicense").jqGrid('getCell', selectedRowId, 'Used');
if (Used == '1') {
if (Count > 0) {
Count = Count - 1;
var rowData = $('#AvailableLicense').jqGrid('getRowData', selectedRowId);
rowData.U_NoUsers = Count;
$('#AvailableLicense').jqGrid('setRowData', selectedRowId, rowData);
}
else
$(this).MessageBox('error', 'License Exhausted');
}
else {
Count = Count + 1;
var rowData = $('#AvailableLicense').jqGrid('getRowData', selectedRowId);
rowData.U_NoUsers = Count;
$('#AvailableLicense').jqGrid('setRowData', selectedRowId, rowData);
}
}
return true;
}
else
$(this).MessageBox('error', 'Please select user first');
},
rowNum: 10,
mtype: 'POST',
pager: "#AvailableLicenseMap",
gridview: true,
rownumbers: true,
loadonce: true, forceFit: true,
width: 600,
height: 250,
caption: 'Available License'
}).jqGrid('navGrid', '#AvailableLicenseMap', { edit: false, add: false, del: false, search: false }); //.trigger('reloadGrid') ;
}
}
});
But I found that rowselectevent does not works properly when I tick the checkbox.
1. When I select the first row event fires.
2. When I reselect the same row it does not fire.
3. After selecting the row If I change the value of checkbox, it doesn't fire event.
May be I don't understand it properly.
It seem to me that you could simplify your code by usage formatoptions: { disabled: false } in the column 'Used' having formatter: 'checkbox'. In the case you don't need to use any editing mode at all. To make actions on checking/unckecking of the checkbox from the column 'Used' one can use beforeSelectRow callback. Look at the demo which I created for the answer. The demo tests for the click inside of the column closed (you need change closed to Used of cause). To make some actions in case of clicking on the checkboxs only one need to change the line if (cm[iCol].name === "closed") { to if (cm[iCol].name === "Used" && e.target.tagName.toUpperCase() === "INPUT") {