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") {
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 have this code below for my jq Grid
function LeaveHalfDay() {
var url1 = URL
$("#LeaveHalfDayDataEntryList").jqGrid({
url: url1,
datatype: 'json',
mtype: 'POST',
colNames: ['RowId', 'With Halfday <br /> Morning', 'With Halfday <br /> Afternoon', 'Date', 'Day'],
colModel: [
{ name: 'rowId', index: 'rowId', hidden: true, editable: true, sortable: false, width: 80, align: 'left' },
{name: 'cbox_leave_half', index: 'cbox_leave_half', editable: true, formatter: cboxFormatterLeaveHalfDay, formatoptions: { disabled: false }, edittype: 'checkbox', editoptions: { value: "True:False" }, sortable: false, width: 70, align: 'center' },
{ name: 'cbox_leave_halfPM', index: 'cbox_leave_halfPM', editable: true, formatter: cboxFormatterLeaveHalfDayPM, formatoptions: { disabled: false }, edittype: 'checkbox', editoptions: { value: "True:False" }, sortable: false, width: 70, align: 'center' },
{ name: 'LStartDate', index: 'LStartDate', editable: false, sortable: false, width: 70, align: 'left' },
{ name: 'LDate', index: 'LDate', editable: false, sortable: false, width: 70, align: 'left' }
],
pager: $('#LeaveHalfDayDataEntryPager'),
rowNum: 5,
rowList: [5, 10, 20],
sortname: '',
sortorder: '',
viewrecords: true,
imgpath: '/Content/themes/redmond/images/',
height: '100%',
loadComplete: function (result, rowid) {
var ids = jQuery("#LeaveHalfDayDataEntryList").getDataIDs();
var len = ids.length, newLine;
if (len < 5) {
AddNewRowToGrid(len, "#LeaveHalfDayDataEntryList");
}
$("#LeaveHalfDayDataEntryPager").css("width", "auto");
$("#LeaveHalfDayDataEntryPager .ui-paging-info").css("display", "none");
}
});
return false;
}
And this one is to click the check box name (cbox_leave_half)
$('.cbox_leave_half').live('click', function (e) {
var tr = $(e.target).closest('tr');
var target = $(e.target).is(':checked');
HalfDayrowsObj[tr[0].id].HalfDay = $(e.target).is(':checked');
_hashalfday = _hashalfday + 1;
var EmployeeId = $("#hidEmployeeId").val();
var StartDate = $("#LSDate").val();
var EndDate = $("#LEDate").val();
var noofdays = $("#txtNoDays").val();
if (StartDate != "" && EndDate != "") {
if (HalfDayrowsObj[tr[0].id].HalfDay == true) {
NoOfHalfDay = NoOfHalfDay + 4;
ComputeTotalDayHourLeave(EmployeeId, StartDate, EndDate, NoOfHalfDay);
noofdays = parseFloat(noofdays) - parseFloat('.5');
$("#txtNoDays").val(noofdays);
$("#hidNoofDays").val(noofdays);
$("#txtNoHrs").val(noofdays * 8);
}
else {
NoOfHalfDay = NoOfHalfDay - 4;
ComputeTotalDayHourLeave(EmployeeId, StartDate, EndDate, NoOfHalfDay);
}
}
});
For example I have 3 data which means I got 6 check boxes inside my JQgrid 3 for AM and 3 for PM. What i want to achieve is if i check the row 0(First row) AM check box it will check, then If i check the PM check box with the same row the PM checkbox must be uncheck. I try to use this code
if ($('.cbox_leave_half').is(':checked))
{ $('.cbox_leave_halfPM').attr("checked",false); }
But this code return all the PM check box will uncheck. What I want is to uncheck the AM/PM with the same row.
I'm using jquery <= 1.8.2 version. I know this is so old but I don't know if I switch to higher version of jquery what will happen to my project.
Could you please try with below code:
Its part of your above code
$('.cbox_leave_half').live('click', function (e) {
var tr = $(e.target).closest('tr');
var target = $(e.target).is(':checked');
if ($(this).is(':checked))
{
$(tr).find('.cbox_leave_halfPM').attr("checked",false);
}
...
...
Here on click of .cbox_leave_half we are searching for associated .cbox_leave_halfPM present in same row i.e. tr element. I hope this will hep you a bit.
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.
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'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"
});