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.
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 am using jqGrid 4.15.6-pre - free jqGrid:
I have two dropdown list in my edit form.
Both are populated from server using the setColProp in the onSelectRRow function.
What I want to do reload the second dropdown list if the value in the first dropdown is changed.
I need to do this without having to close the edit form.
The example below uses the Guriddo jqGrid. You maybe can adapt it to the forked version - free-jqgrid.
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'data.json',
editurl: 'clientArray',
datatype: "json",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 75,
key: true
},
{
label: 'Company Name',
name: 'CompanyName',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label : 'Phone',
name: 'Phone',
width: 100,
editable: true
},
{
label: 'Postal Code',
name: 'PostalCode',
width: 80,
editable: true
},
{
name: 'Country',
width: 200,
editable: true,
edittype: "select",
editoptions: {
value: "USA:USA;UK:UK;Canada:Canada"
}
},
{
name: 'City',
width: 200,
editable: true,
edittype: "select",
editoptions: {
value: "Select a City"
}
}
],
loadonce: true,
viewrecorde: true,
width: 780,
height: 200,
rowNum: 10,
pager: "#jqGridPager"
});
$('#jqGrid').navGrid('#jqGridPager',
// the buttons to appear on the toolbar of the grid
{ edit: true, add: false, del: false, search: false, refresh: false, view: false, position: "left", cloneToTop: false },
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
recreateForm: true,
closeAfterEdit: true,
viewPagerButtons: false,
afterShowForm: populateCities,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
// This function gets called whenever an edit dialog is opened
function populateCities() {
// first of all update the city based on the country
updateCityCallBack($("#Country").val(), true);
// then hook the change event of the country dropdown so that it updates cities all the time
$("#Country").bind("change", function (e) {
updateCityCallBack($("#Country").val(), false);
});
}
function updateCityCallBack(country, setselected) {
var current = $("#jqGrid").jqGrid('getRowData',$("#jqGrid")[0].p.selrow).City;
$("#City")
.html("<option value=''>Loading cities...</option>")
.attr("disabled", "disabled");
$.ajax({
url: country+".html",
type: "GET",
success: function (citiesHtml) {
$("#City")
.removeAttr("disabled")
.html(citiesHtml);
if(setselected) {
$("#City").val( current );
}
}
});
}
});
Real-time example is here
I am using jqgrid. I want to allow people to use a checkbox in inline editing. There will not be any buttons like edit etc, As soon as he clicks the checkbox, it should be considered as committed on client side.
There is a checkbox which I want to always keep in edit mode. After user is done making changes, he will click on a submit button & full grid data will get posted to the server.
I expect that getGridParam method should give me the updated cell values. However it is not doing so.
I feel my problem is the onSelectRow method. somewhere I am missing the implementation to save the current row state. & hence in the getGridParam method. I am getting the original values.
Code :
var lastsel;
jQuery("#AcOpenDataGrid").jqGrid({
url: '/Admin/Role/GetMappedMenus',
viewrecords: true, sortname: 'Code', sortorder: "desc",
colNames: [
"Code",
"MenuName",
"Allow"
],
colModel: [
{ name: 'Code', width: 10, key: true, align: 'center', hidden: true },
{ name: 'MenuName', index: 'MenuName', width: 60, search: true, searchoptions: JQ_sopt_string, align: 'left' },
{ name: 'Allow', index: 'Allow', width: 30, editable: true,edittype:'checkbox',editoptions: { value:"True:False" },formatter:'checkbox', formatoptions: {disabled : false} ,search: true, searchoptions: JQ_sopt_string, align: 'center' },
],
height: '500',
autowidth: true,
rowList: JQ_Paging_Opt,
rowNum: JQ_RowNum_Opt,
pager: pager_selector,
datatype: 'json', mtype: 'GET',
cmTemplate: { title: false },
loadonce:true,
altRows: true,
jsonReader: { root: "rows", page: "page", total: "total", records: "records", repeatitems: false, userdata: "userdata", id: "Code" },
editurl: 'clientArray',
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery(grid_selector).jqGrid('restoreRow', lastsel);
//jQuery(grid_selector).jqGrid('saveRow', lastsel);
jQuery(grid_selector).jqGrid('editRow', id, true);
lastsel = id;
}
},
}).navGrid(pager_selector, { view: false, del: false, add: false, edit: false, search: false, refresh: true }
).jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: 'cn' });
});
$(".submit").click(function () {
var localGridData = $("#AcOpenDataGrid").jqGrid('getGridParam', 'data');
//To Do : Post Ajax here.
});
I found a solution here. Not exactly what I expected but it does serves my purpose.
Make a column be a checkbox
beforeSelectRow: function (rowid, e) {
var $self = $(this),
iCol = $.jgrid.getCellIndex($(e.target).closest("td")[0]),
cm = $self.jqGrid("getGridParam", "colModel"),
localData = $self.jqGrid("getLocalRow", rowid);
if (cm[iCol].name === "closed") {
localData.closed = $(e.target).is(":checked");
}
return true; // allow selection
},
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
When I click second time jquery grid is not working.
$(document).ready(function() {
$('#btnlinechat').click(function() {
debugger;
var firstClick = true;
if (!firstClick) {
$("#list").trigger("reloadGrid");
}
firstClick = false;
//var getdata = function () {
//debugger;
var arr = {};
var datefromt = document.getElementById('txtfrom').value;
var datetot = document.getElementById('txtto').value;
arr.StartDate = datefromt;
arr.EndDate = datetot;
$.ajax({
//mtype: 'GET',
type: "POST",
contentType: "application/json",
//data: "{}",
data: JSON.stringify(arr),
url: "buttontest.aspx/GetData",
dataType: "json",
success: function(data) {
data = data.d;
$("#list").jqGrid({
datatype: "local",
colNames: ['Monthly Topup', 'Monthly Payout', 'Balance', 'Monthly Date'],
colModel: [{
name: 'monthlytopup',
index: 'monthlytopup',
width: 10,
height: 30,
editable: false
}, {
name: 'monthlypayout',
index: 'monthlypayout',
width: 10,
height: 30,
editable: false
}, {
name: 'balance',
index: 'balance',
width: 10,
height: 30,
editable: false
}, {
name: 'monthlydate',
index: 'monthlydate',
width: 10,
formatter: 'date',
formatoptions: {
srcformat: "Y-m-d",
newformat: 'd/m/y',
datefmt: 'd/m/y'
}
}
],
data: JSON.parse(data),
rowno: 10,
loadonce: false,
rowlist: [5, 10, 20],
pager: '#pagingGrid',
viewrecords: true,
gridview: true,
sortorder: 'asc',
rownumbers: true,
//altrows: true,
reload: true,
autowidth: false,
hoverrows: true,
height: 300,
//multiselect: false,
width: 1345,
rownumbers: true,
caption: "DATA",
});
debugger;
$('#list').jqGrid('navGrid', '#pagingGrid', {
edit: false,
add: false,
del: false,
search: true,
searchtext: "Search",
viewrecords: true,
reload: true,
//cloneToTop: false,
});
},
});
//}
});
});
Every click is treated as the first since you explicitly say so in your click handler:
var firstClick = true;
Instead this should look something like:
var firstClick = true; // << Outside the click handler
$(document).ready(function() {
$('#btnlinechat').click(function() {
debugger;
if (!firstClick) {
$("#list").trigger("reloadGrid");
}
...
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") {