Jqgrid and Data send error - ajax

I have this code..
var _codSelected="";
$("#list").jqGrid({
url: '/modulos/mantenimiento/Proveedores.ashx',
datatype: 'xml',
mtype: 'GET',
colNames: ['Codigo' //Some more colnames and colmodels]
colModel: [{ name: 'Codigo', index: 'PRg_Codigo', edittype: 'select',
editable: true, editrules: { edithidden: false }, editoptions:
{ size: 30, dataUrl: '/modulos/mantenimiento/grupoProveedores.ashx?
oper=selectAllGroups }, sortable: true }
],
onSelectRow: function (rowid) {
_codSelected = rowid;
//alert(_codSelected);
},
When i select a row in my jqgrid, the alert (commented) is show me the value that i want to send by dataUrl to my handler, but always is empty. The alert shows it, but i cant include it in the url! Can someone tell me how can i do it?
Thanks.
EDIT
I have fixed adding this event..
ajaxSelectOptions: {
data: {
codSelected: function () {
return _codSelected;
}
}
}

That's because _codSelected is just an empty string in the scope of the colModel array declaration. It only becomes your row id in the callback function.
If you want _codSelected to have a value to append to dataUrl, you need to give it one before referencing it inside your object literal.

Related

Sometimes jqgrid getChangedCell not return checkbox changed

when I insert/update table data. i use getChangedCell function for making input data before call API. like this.
let inputData = _$myTable.getChangedCells('all');
$.ajax({
type: "POST",
url: "/api/services/InsertData",
dataType: "json",
data: inputData
})
Please check sample image.
First I check checkbox. after then click save button.
At this moment, generally _$myTable.getChangedCells('all') return the correct value.
But, sometimes _$myTable.getChangedCells('all') return []
Table options are :
_$myTable.jqGrid({
mtype: "GET",
datatype: "local",
autowidth: true,
shrinkToFit: false,
cellEdit: true,
colModel: [
{
name: "id",
key: true,
hidden: true
},
...
],
onSelectRow: function (id) {
if (id && id !== optionlastsel) {
_$myTable.jqGrid('restoreRow', optionlastsel);
_$myTable.jqGrid('editRow', id, true);
optionlastsel = id;
}
},
afterEditCell: function (rowid, cellname, value, iRow, iCol) {
var checkboxNameSet = _.pluck(_.where(_$myTable.jqGrid("getGridParam").colModel, { edittype: 'checkbox' }), 'name');
if (checkboxNameSet.includes(cellname)) {
$('#' + rowid + '').addClass("edited");
}
}
})
Checkbox options are:
{
label: 'IsActive',
name: "isActive",
editable: true,
edittype: 'checkbox',
editoptions: { value: "true:false" },
editrules: { required: true },
formatter: "checkbox",
formatoptions: { disabled: false },
align: "center"
}
In addition, all the time, the network was fine.
Are there any options I missed or mistake?
Thank you for reading.

jqgrid - dynamically change mask based on a previous column value

I am using jquery.maskedinput-1.3.js
In column 1, are the phone types. In column 2 the phone numbers.
{ name: 'PhoneTypeId', index: 'PhoneTypeId', hidden: true, editable: true, sortable: true},
{ name: 'Phone', index: 'Phone', width: 150, editable: true, editoptions: { dataInit: function (elem) { $(elem).mask("(999) 999-9999"); }, dataEvents: [{ type: 'change', fn: function (e) { hasChanges=true } }]}, editrules:{required: true}, sortable: true },
I'd like to dynamically change the mask based on the type of phone. Is this possible?
My data is json serialized objects:
datatype: "local",
data: #Html.Raw(ViewBag.Phones)
editurl: 'clientArray'
Thanks,
Gen
You can add change event (using dataInit) of the phone type and based on this you can change the mask (if this plugin allows this). Initially when you start editing (depending on the edit type - form edit or inline edit) you can use some events before editing by example beforeShowForm for form edit or beforeEditRow for inline edit. If you use Guriddo jqGrid JS you can look at the documentation here
EDIT:
In case the field phonetype is not editable by the user then
{ name: 'Phone', index: 'Phone', width: 150, editable: true,
editoptions:{
dataInit: function (elem, options) {
// use the id of the row
var id = options.rowId;
// content of the phonetype cell
var phonetypeval = $(this).jqGrid('getCell', id, 'PhoneTypeId')
if( phonetypeval === 'something') {
mask = 'mask1';
} else {
mask = 'mask2';
}
$(elem).mask(mask);
},
dataEvents: [{
type: 'change', fn: function (e) { hasChanges=true } }
]}
, editrules:{required: true},
sortable: true}
Note that this code is valid for inline and form edit.

Hide navgrid buttons depending on the number of records in jqgrid

I need to hide the delete button if there are less than 2 records in the grid. This is the js code. For some reason, the flag showDelCurrencyButton is not working out here and is always false.
Any other way to do it?
showDelCurrencyButton = false;
grid.jqGrid({
datatype: 'local',
jsonReader: jqgrid.jsonReader('CurrCd'),
mtype: 'POST',
pager: '#currencyPager',
colNames: ['Abbrev.', 'Name', 'Symbol'],
colModel: [
{
name: 'CurrCd', index: 'CurrCd', width: 200, sortable: false,
editable: true,
edittype: 'select', stype: 'select',
editrules: { required: true },
editoptions: {
dataUrl: getServerPath() + 'Ajax/GetCurrencies',
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: 'CurrName', index: 'CurrName', width: 200, sortable: false },
{ name: 'CurrSymbol', index: 'CurrSymbol', width: 200, sortable: false },
],
loadtext: 'Loading...',
caption: "Available Currencies",
scroll: true,
hidegrid: false,
height: 116,
width: 650,
rowNum: 1000,
altRows: true,
altclass: 'gridAltRowClass',
onSelectRow: webview.legalentities.billing.onCurrencySelected,
loadComplete: function (data) {
if (data.length > 1) {
showDelCurrencyButton = true;
}
var rowIds = $('#currencyGrid').jqGrid('getDataIDs');
$("#currencyGrid").jqGrid('setSelection', rowIds[0]);
},
rowNum: 1000
});
grid.jqGrid('navGrid', '#currencyPager', {
edit: false,
del: (showDelCurrencyButton == true),
deltitle: 'Delete record',
search: false,
refresh: false
}
});
Your current code uses datatype: 'local' without specifying data parameter with input data. It seems strange. In any way you can hide the Delete button dynamically identifying it by id. It's "del_" + grid[0].id in your case. Thus you can use $("#del_" + grid[0].id).hide(); to hide it. By the way one can use this instead of grid[0] inside of loadComplete.
I'd recommend you to read the old answer for more details and to read the answer, which shows how to disable/enable navigator buttons (like Delete button) instead of hiding.

JQGrid, Edit Url

I am new to jQuery, and I need to use jqGrid in my project.
I have one problem with edit/delete/insert; I have only one URL, editurl, then in the controller I am using the oper property to decide whether it is an insert or delete operation.
But I want to have a separate URL for the edit, delete and insert operations in jqGrid. Could you please let me know how to achieve that?
Client side code:
$(document).ready(function () {
var lastsel2;
var grid = jQuery("#list5").jqGrid({
url: '/home1/GetUserData',
datatype: "json",
mtype: "POST",
colNames: ['Code', 'LoginID', 'Emailid', 'CreateDate'],
colModel: [
// { name: 'act', index: 'act', width: 75, sortable: false },
{name: 'Code', index: 'Code', width: 55, editable: true },
{ name: 'LoginID', index: 'LoginID', width: 90, editable: true },
{ name: 'Emailid', index: 'Emailid', width: 100, editable: true },
{ name: 'CreateDate', index: 'CreateDate', width: 100, editable: true }
],
rowNum: 10,
width: 700,
height: 300,
rowList: 10,
pager: $("#pager2"),
editurl: "/home1/EditUserData",
onSelectRow: function (id) {
if (id && id !== lastsel2) {
if (id == "new_row") {
grid.setGridParam({ editurl: "/home1/InsertUserData" });
}
else {
grid.setGridParam({ editurl: "/home1/EditUserData" });
}
jQuery('#list5').restoreRow(lastsel2);
$("#list5_ilsave").addClass("ui-state-disabled");
$("#list5_ilcancel").addClass("ui-state-disabled");
$("#list5_iladd").removeClass("ui-state-disabled");
$("#list5_iledit").removeClass("ui-state-disabled");
lastsel2 = id;
}
},
caption: "Simple data manipulation"
});
jQuery("#list5").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {}, { url: '/home1/DeleteUserData' });
jQuery("#list5").jqGrid('inlineNav', "#pager2", { edit: true, add: true, del: true, search: false, refresh: false });
});
You can pass options for all the actions with navGrid method like this:
jQuery('#list5').jqGrid('navGrid', '#pager2', { edit: true, add: true, del: true },
//edit options
{ url: '/home1/EditUserData' },
//add options
{ url: '/home1/AddUserData' },
//delete options
{ url: '/home1/DeleteUserData' }
);
Please read more here and here.
UPDATE
In case of inlineNav method jqGrid is always passing the same set of parameters (editParams) to saveRow method. As the effect the edit/add request will be made to the same URL. You are sticked with checking oper to distinguish edit for add.
In the subject of reloading the grid you can use editParams to set aftersavefunc to trigger realoadGrid like this:
jQuery('#list5').jqGrid('inlineNav', '#pager2', { edit: true, add: true, editParams: {
aftersavefunc: function(rowId, response) { jQuery('#list5').trigger('reloadGrid'); }
}});
But you should remember that it will also cause a refresh after edit (because of the same reason as described above) - you may try to use response parameter to distinguish those two. I have also removed del, search and refresh from the code as inlineNav doesn't have those options.

jqGrid Switch a field to dropdown from text

Ive got a jqGrid where i have a some columns and 1 of the columns is a dropdownlist(select) populated from database.
What i want is : When im not in editmode column with dropdowns just have to show text which have to be taken from query, and when im in edit mode it should show dropdown list.
exactly like here: http://www.trirand.com/blog/jqgrid/jqgrid.html go into row editing/input tipyes
here is the code for my grid:
<script type="text/javascript">
var lastsel;
$(document).ready(function () {
$.getJSON('#Url.Action("ConstructSelect")', function (data) {
setupGrid(data);
});
});
function setupGrid(data) {
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("GetStoreList")',
datatype: 'json',
mtype: 'GET',
colNames: ['Butiks kategori', 'Butik Navn', 'By', 'Sælger'],
colModel: [
{ name: 'Id', index: 'Id', width: 50 },
{ name: 'Butiks Kategori', index: 'StoreId', width: 200, edittype: 'text', align: 'center', editable: false },
{ name: 'Buttiks Navn', index: 'StoreName', width: 200, edittype: 'text', align: 'center', editable: false },
{ name: 'Country', index: 'Country', width: 80, sortable: true, editable: true, edittype: "select", editoptions: { value: data }}],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("GridSave")',
rowNum: 50000,
rowList: [5, 10, 20, 50],
pager: '#page',
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
height: "500px",
imgpath: '/scripts/themes/base/images'
});
jQuery("#list").jqGrid('navGrid', "#page", { edit: false, add: false, del: false });
});
}
</script>
P.S. Ill link code as soon as i am back home
UPDATED: Thanks for an answer, im new to jq, so im making alot of mistakes ofc., but now im back to where i was before, the dropdownlist is not populated with data. i cleaned up the code as u said, so it looks like this now:
btw. The ConstructSelect return a list of Strings
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("GetStoreList")',
ajaxSelectOptions: { type: "POST", dataType: "json" },
datatype: 'json',
mtype: 'GET',
colNames: ['Butiks kategori', 'Butik Navn', 'By', 'Sælger'],
colModel: [
{ name: 'Kategori', index: 'Kategori', width: 50, key: false},
{ name: 'Navn', index: 'Navn', align: 'center', editable: false },
{ name: 'By', index: 'By', align: 'center', editable: false },
{ name: 'Sælger', index: 'Sælger', editable: true, edittype: "select",
editoptions: { dataUrl: '#Url.Action("ConstructSelect")',
buildSelect: function (data) {
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
var ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + "</select>";
}
}
}],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("GridSave")',
rowNum: 50000,
rowList: [5, 10, 20, 50],
pager: '#page',
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
height: "900px"
});
jQuery("#list").jqGrid('navGrid', "#page", {edit:false, add:false, del:false});
});
Okay, slight modifications was needed to get it working :
var response = typeof(data) === "string" ? jQuery.parseJSON(data.responseText):data;
aparently u have to tell buildselect that the data u want to modify is String
But i still have the problem that it doesnt show from begining which sellers is already selected!
Okay after restart it mysticly worked... it is solved now
What you need to do is to use
editoptions: { dataUrl: '#Url.Action("ConstructSelect")' }
instead of
editoptions: { value: data }
Depend on the format of the output of the action ConstructSelect you can need to use an additional property buildSelect of the editoptions. jqGrid expected that the server response on the HTTP 'GET' request of dataUrl will be HTML fragment which represent <select>. For example:
<select>
<option value="de">Germany</option>
<option value="us">USA</option>
</select>
If the server return other formatted data, like JSON data
["Germany","USA"]
or
[{"code":"de","display":"Germany"},{"code":"us","display":"USA"}]
you can write JavaScript function which convert the server response to the HTML fragment of the <select> and set the value of the property buildSelect to the function.
In the answer you will find an example of the function.
If your action support only HTTP POST and no GET you will have to use ajaxSelectOptions: { type: "POST" } parameter additionally, to overwrite the type of the corresponding ajax requests. In the same way you can overwrite other ajax parameters. For example you can use
ajaxSelectOptions: { type: "POST", dataType: "json"}
(defaults are type : "GET" and dataType: "html")
Some other small remarks to the code:
you should not place $(document).ready(function () { inside of another $(document).ready(function () {.
You use 'Id' instead of 'id'. So jqGrid will not find the id property. You can a) rename
'Id' to 'id' b) include additional parameter jsonReader: {id: 'Id'} c) include additional property key: true in the definition of the column 'Id'. Any from the ways will solve the described problem.
You can remove default properties like edittype: 'text', sortable: true or editable: false. See jqGrid documentation which describes the default values of all colModel properties.
You should remove imgpath parameter of jqGrid. The parameter is not exist since many many versions of jqGrid (see here).

Resources