jqgrid addrowdata after calling ajax - javascript

I have question regarding adding another rowdata at the end of my jqgrid. What I wanted to do is that everytime I do a simple search on a particular transaction, and display it on my jqgrid, i want to have another row at the end which have my total computations. Below is my complete jqgrid code:.
$("#tblSupplier").jqGrid({
url: '',
datatype: 'local',
jsonReader : {
root: function(obj) {
var root = [];
if ('error' in obj)
{
showMessage(obj.error['class'] + ' error: ' + obj['error']['msg']);
}
else
{
var totalBdFt = '';
var bdft=0;
var amt=0;
var totalAmount = '';
$.each(obj['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = obj['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
if (fldName == 'transaction_date'){
$('#tallyDate').val(rowArrayValue);
}
if (fldName == 'supplier_name'){
$('#supplierName').val(rowArrayValue);
}
if (fldName == 'board_foot'){
bdft = parseFloat(bdft) + parseFloat(rowArrayValue);
}
if (fldName == 'total_amount'){
amt = parseFloat(amt) + parseFloat(rowArrayValue);
}
});
root[rowIndex] = row;
$('#totalBdft').val(parseFloat(bdft));
$('#totalAmt').val(parseFloat(amt));
});
};
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("SessionID"),
'dataType': 'data',
'simple_search_value':trim($("#searchSupAny").val()),
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Transaction Num', 'Wood Classification', 'Specie', 'Total Board Foot', 'Price', 'Total Amount'],
colModel:[
{name:'transaction_num'},
{name:'wood_classification_desc'},
{name:'wood_specie_desc'},
{name:'board_foot'},
{name:'price'},
{name:'total_amount'}
],
viewrecords: true,
sortname: 'transaction_num',
sortorder: 'desc',
loadonce:false,
height:'100%',
caption: "sample summary"
});
var newRowData = [{ "wood_classification_desc": 'total should b here', "wood_specie-desc": "total bdft here", "total_amount": "total amount here"}];
$("#tblSupplier").addRowData('transaction_num',newRowData);
})
my newRowData displays only on load, but after I do a simple search, it will also gone. But my jqgrid with ajax data working good. So how should I do it to maintain my additional row everytime I call ajax?

Related

disallow blank/empty cells in kendo grid

How could I disallow a cell in my kendo grid to be 'blank' or 'empty' rather... How could I replace all blank or empties with a 0..
I have a save button grabbing the values from my kendo grid such as below: Everything works fine EXCEPT, it is completely omitting my empty cells.. I want to keep them, just have a 0 value on them...
Save button: want to keep the empties with simply a 0 or N/A..
$('.' + chs).on('click', '#saveChanges', function(e) {
which = $(frm).attr("class");
let dataSource = $("#grid").data("kendoGrid").dataSource,
data = dataSource.data(),
changedModels = [];
if(dataSource.hasChanges) { // only saves cells/row that have been edited/changed, need to keep this
for(var i = 0; i < data.length; i++) {
if(data[i].dirty) { changedModels.push(data[i].toJSON()) }
}
}
let ds = JSON.stringify(changedModels);
$.ajax({
type: "POST",
url: "saveGrid",
dataType: "json",
data: {
id: which,
data: ds
},
success: function(result) {
console.log('yy');
},
error: function(result) {
console.log('nn');
}
});
});
This is my kendo grid initialized:
let dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/popGrid?id=" + which,
dataType: "json"
},
},
batch: true,
schema: {
data: "data",
model: {
id: id,
}
},
});
console.log(id);
$("#grid").kendoGrid({
dataSource: dataSource,
height: 600,
sortable: true,
autoBind: true,
nullable: true,
editable: {
createAt: "top"
},
change: function(e) {
let grid = $("#grid").data("kendoGrid");
let selectedItem = grid.dataItem(grid.select());
let val = selectedItem.id;
console.log(val);
},
selectable: "row",
toolbar: [
{ name: "create" },
{ name: "cancel" }
],
paging: false,
});
I can't understand if you want to POST empty fields as "0" or if you want to SHOW them in the grid as "0", when null or "empty".
But I guess you're talking about posting it as "0". In that case I think you have to do that before posting:
let fieldName = 'myCell';
if (data[i].dirty) {
if (!data[i].hasOwnProperty(fieldName) || // In case field is not present on data
!data[i][fieldName]) { // In case field value is null/undefined/0/false/empty string
data[i][fieldName] = 0;
}
changedModels.push(data[i].toJSON());
}
For multiple field check:
let fieldNames = ['fieldA', 'fieldB', ...],
checkFields = (item) => {
fieldNames.forEach(field => {
if (!item.hasOwnProperty(field) || // In case field is not present on data
!item[field]) { // In case field value is null/undefined/0/false/empty string
item[field] = 0;
}
});
};
Or you can do the same before data is bound to the grid with dataSource.schema.parse.

JQgrid show message before update and multiple update

I am working on JQgrid and trying to achieve some specific functionality. These functionalists are
1)inline update with message shown before update.
2)Multiple update
I tried to read jqgrid and got this code https://jsfiddle.net/OlegKi/byygepy3/11/ . Which is quite approximate to my requirement but it doesn't contain multiple update and message shown before update.
I tried to overwrite these code but maximum i reached is this https://jsfiddle.net/byygepy3/72/ but failed because multiple update only updating half of record and it doesn't show any message before updating either single row or multiple row.
code is inserting just allow me to ask question.
$(function () {
var myData = [
{ id: 10, ParameterName: "Test", ParameterValue: "" },
{ id: 20, ParameterName: "Test 1", ParameterValue: "" },
{ id: 30, ParameterName: "Test 2", ParameterValue: "" },
{ id: 40, ParameterName: "Test 2", ParameterValue: "" },
{ id: 50, ParameterName: "Test 2", ParameterValue: "" },
{ id: 60, ParameterName: "Test 2", ParameterValue: "" }
],
$grid = $("#list");
// change the text displayed on editrules: {required: true }
$.extend(true, $.jgrid.locales["en-US"].edit.msg, {
required: "No value was entered for this parameter!!!"
});
$grid.jqGrid({
datatype: "local",
data: myData,
colNames: ["", "Parameter Name", "Parameter Value"],
colModel: [
{ name: "act", template: "actions" }, // optional feature
{ name: "ParameterName" },
{ name: "ParameterValue", editable: true,
editoptions: { maxlength: 100 }, editrules: {required: true } }
],
cmTemplate: { autoResizable: true },
autoResizing: { compact: true },
pager: true,
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: true, // disable current view record text like 'View 1-10 of 100'
sortname: "Name",
iconSet: "fontAwesome",
caption: 'Parameters',
autowidth: true,
hidegrid: false,
inlineEditing: {
keys: true
},
singleSelectClickMode: "selectonly", // prevent unselect once selected rows
beforeSelectRow: function (rowid) {
// allow selection if saving successful
},
onSelectRow: function (rowid) {
$(this).jqGrid("editRow", rowid);
},
afterSetRow: function (options) {
var item = $(this).jqGrid("getLocalRow", options.rowid);
if (item != null) {
item.dirty = true;
}
},
navOptions: {
edit: false,
add: false,
search: false,
deltext: "Delete",
refreshtext: "Refresh"
},
inlineNavOptions: {
save: false,
savetext: "Save",
cancel: false,
restoreAfterSelect: false
},
formDeleting: {
// delete options
url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
beforeSubmit: function () {
// get value
var selRowId = $(this).jqGrid('getGridParam', 'selrow');
var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');
// check if empty
if (parametricValue === "") {
return [false, "Cannot delete: No value exists for this parameter"];
}
return [true, "Successfully deleted"];
},
delData: {
batchId: function () {
return $("#BatchId").val();
}
},
closeOnEscape: true,
closeAfterDelete: true,
width: 400,
msg: "Are you sure you want to delete the Parameter?",
afterComplete: function (response) {
if (response.responseText) {
alert("response.responseText");
}
//loadBatchListIntoGrid();
}
}
}).jqGrid('navGrid')
.jqGrid('inlineNav')
.jqGrid('navButtonAdd', {
caption: "Save Changed",
buttonicon: "fa-floppy-o",
onClickButton: function () {
var $self = $(this), i,
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
$self.jqGrid("saveRow", savedRows[i].id);
}
var localData = $(this).jqGrid("getGridParam", "data"),
dirtyData = $.grep(localData, function (item) {
return item.dirty;
});
alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
}
});
// make more place for navigator buttons be rwducing the width of the right part
var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
$(pagerIdSelector + "_right").width(100);
// make the grid responsive
$(window).bind("resize", function () {
$grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
}).triggerHandler("resize");
});
Free jqGrid supports a lot of callbacks, which will be used during saving the rows. You can use for example beforeSaveRow callback of inline editing, custom validation via editrules.custom callback function, beforeSelectRow and other. Additionally, your code seems to distinguish the initial empty value "" of ParameterValue column from any other values. The final code you should made yourself. I posted an example
beforeSelectRow: function (rowid) {
// allow selection if saving successful
var $self = $(this), i,
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
if (rowid !== savedRows[i].id) {
if (allowSaving.call(this, savedRows[i].id)) {
$self.jqGrid("saveRow", savedRows[i].id);
} else {
$self.jqGrid("restoreRow", savedRows[i].id);
}
}
}
return true;
},
with allowSaving function defined as
var allowSaving = function (rowid) {
var item = $(this).jqGrid("getRowData", rowid);
if (item.ParameterValue !== "") {
return confirm("Do you want to save \"" +
item.ParameterValue + "\" value in \"" +
item.ParameterName + "\"?");
} else {
return false;
}
};
It allows to ask the user to confirm the changes of ParameterName. Additionally the code of "Save Changed" button should be adjusted too.
See https://jsfiddle.net/OlegKi/byygepy3/74/

Using an external auto complete plugin (jQuery) and i am trying to put my own value in json it was not working

This is the continuation with my previous question posted here I am new to the JSON and ajax trying to put my own value in this link the data as per my requirement.
$("document").ready(function() {
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function(index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function(index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function(ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function(index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
//from here I am customizing the code*/
$("document").ready(function (){
$("#scl_name").mcautocomplete({
// These next two options are what this plugin adds to the autocomplete widget.
showHeader: true,
showHeader: true,
columns: [{
name: 'description',
width: '150px'
}, {
name: 'schoolname',
width: '120px'
}],
// Event handler for when a list item is selected.
/*select: function (event, ui) {
this.value = (ui.item ? ui.item.name : '');
$('#school_Name').text(ui.item ? 'Selected: ' + ui.item.name +this.value);
return false;
},*/
// The rest of the options are for configuring the ajax webservice call.
minLength: 1,
source: function (request, response) {
$.ajax({
url: 'dummy.json',
dataType: 'json',
data: {
featureClass: 'P',
style: 'full',
maxRows: 12,
name_startsWith: request.term,
username: "demo"
},
// The success event handler will display "No match found" if no items are returned.
success: function (data) {
var result;
if (!data || data.length === 0 || !data.schoolname || data.schoolname.length === 0) {
result = [{
label: 'No match found.'
}];
} else {
result = data.schoolname;
console.log(result);
}
response(result);
}
});
}
});
});
with the current one i am getting the output as [object] Now I am not getting any error but i am not getting any value as well :(
This is my html
<input type="text" id="scl_name" class="ipt_Field"/>
Thanks in advance

Define custom sorting on free jqgrid

I have a column called InterestedValue, where I would like to allow sorting, by the label of the dropdown.
I found similar questions and I implemented the recommended solution, but it does not work.
Essentially, nothing happens, the applications behaves exactly like before we added the custom sorttype. Even adding alerts in it, nothing happens, get no errors, or anything.
{
name: 'InterestedValue', editable: true, sortable: true, formatter: 'select', width: 110, search: false, edittype: 'select',
editoptions: {
value: InterestedStatusList,
},
sorttype: function (cellvalue)
{
return InterestedStatusList[cellvalue];
}
}
I added the loadonce: true as suggested, and now I can sort the data correctly, but when I have more records than the ones shown in the first screen, I cannot visualize them.
My code is:
$(gridId).jqGrid(//'setGroupHeaders',
{
url: actionMethod,
shrinkToFit: false,
datatype: 'json',
mtype: 'GET',
loadonce: true,
//sortable: true,
colNames: [MyColumns],
colModel: [
{MyModel }
],
pager: jQuery(pagerId), //jQuery('#pager'),
rowNum: 10,
rowTotal: 2000,
rowList: [10, 20, 30, 40],
height: '100%',
//width:700,
viewrecords: true,
caption: caption,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
//autowidth: true,
multiselect: false,
gridview: true,
editurl: '/InvestorList/Edit',
onSelectRow: function (id) {
if (id) {
$(gridId).jqGrid("editRow", id, true, '', '', '', '', reload)
//ORIGINAL CODE: $(gridId).editRow(id, true,'', '', '', '', reload);
lastSelectedId = id;
}
},
serializeRowData: function (postdata) {
//var response = JSON.stringify(postdata);
var s = '';//'<select>';
$(postdata).each(function (index, data) {
//s += '<option value="' + index + '">' + data + '</option>';
$.each(data, function (k, v) {
if (k == "InterestedValue")
s += v;//'<option value="' + k + '">' + v + '</option>';
});
});
//alert("s=" + s);
if (s.indexOf("100010002") != -1) { //"2_1") {
if (confirm('Are you sure you want to deactivate this record? ')) {
// do things if OK
return postdata;
}
else
return false;
}
return postdata;
},
Essentially I see the first ten records, and I have no way of accessing the remaining ones.
How can I fix this?

how do i assign value to columns in jqGird?

i am using jqGrid with CodeIgniter 2.1.0 .
The thing which is making me harassed is how to assign value to specific column on specific event
Suppose i am entering qty and rate in column value.....and when i loss focus from "rate" field.....the net amount should be calculated and displayed in amount field...
what i need to do here is to assign calculated value to amount field......but i am not getting any idea regarding how do i do it??
what i have done is given below :
var selIRow = 1;
var rowid='';
var iCol='';
$("#purchasedetailsgrid").jqGrid({
url: sitepath + 'purchase/purchase_grid',
datatype: 'json',
mtype: 'POST',
height:220,
width:500,
colNames:["","","Store Name","Item Name","Inner Pkg.","Outer Pkg.","Qty","Rate","Amount"],
colModel:[
{name: 'storeID_hidden_field', index:'storeID_hidden_field',hidden: true, editable: true,edittype: 'text',editrules: {edithidden:true}},
{name: 'itemID_hidden_field', index:'itemID_hidden_field',hidden: true, editable: true,edittype: 'text',editrules: {edithidden:true}},
{name:'store_id', index:'store_id',width:150,search:false,editable:true,editrules:{number:false,maxlength:10}},
{name:'item_id', index:'item_id',width:150,search:false,editable:true,editrules:{number:false,maxlength:10}},
{name:'inner_pkg', index:'inner_pkg',width:150,search:false,editable:true,editrules:{number:true,maxlength:5}},
{name:'outer_pkg', index:'outer_pkg',width:150,search:false,editable:true,editrules:{number:true,maxlength:5}},
{name:'qty', index:'qty',editable:true,width:85,search:false,editrules:{number:true,maxlength:5}},
{name:'rate', index:'rate',width:100,editable:true,search:false,editrules:{number:true,maxlength:10},
editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [
{
type: 'keydown',
fn: function (e) {
var key = e.charCode || e.keyCode;
if (key == 9)//tab
{
$('#amount').val();//here in val() i need to write the value of qty and rate field
}
}
}
]
}
},
{name:'amount', index:'amount',width:100,editable:true,search:false,editrules:{number:true,maxlength:10},
editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [
{
type: 'keydown',
fn: function (e) {
var key = e.charCode || e.keyCode;
if (key == 13)//enter
{
var grid = $('#purchasedetailsgrid');
//Save editing for current row
grid.jqGrid('saveRow', selIRow, false, sitepath + 'purchase/purchase_grid');
selIRow++;
//If at bottom of grid, create new row
//if (selIRow++ == grid.getDataIDs().length) {
grid.addRowData(selIRow, {});
//}
//Enter edit row for next row in grid
grid.jqGrid('editRow', selIRow, false, sitepath + 'purchase/purchase_grid');
}
}
}
]
}
}
],
pager: '#purchasedetailstoolbar',
rowNum:10,
rowList:[10,20,30],
sortname: 'inventory_id',
sortorder: 'desc',
viewrecords: true,
rownumbers: true,
gridview: true,
multiselect: false,
autoresize:true,
autowidth: true,
editurl: sitepath + 'purchase/purchase_grid',
toolbar: [true,"top"],
gridComplete: function ()
{
var grid = jQuery("#purchasedetailsgrid");
var ids = grid.jqGrid('getDataIDs');
if(ids == '')
{
grid.addRowData(selIRow, {});
grid.jqGrid('editRow', selIRow, false, sitepath + 'purchase/purchase_grid');
}
for (var i = 0; i < ids.length; i++)
{
}
},
caption: 'Purchase List',
});
jQuery("#purchasedetailsgrid").jqGrid('navGrid','#purchasedetailstoolbar',{view:false,edit:false,add:false,del:false,search: false});
jQuery("#purchasedetailsgrid").jqGrid('inlineNav','#purchasedetailstoolbar');
jQuery("#purchasedetailsgrid").jqGrid('filterToolbar',{stringResult:false,searchOnEnter : false},{autosearch: true});
var temp_purchase = $("#purchasedetailsgrid_header").html();
$("#t_purchasedetailsgrid").html(temp_purchase);
$("#refresh_purchasedetailsgrid").attr('title',"Reload Grid");
Now can anyone suggest me how will i get value from one column and assign it another?
Any suggestions will be appreciated.
Thnx in advance
You current code have many problems. For example you wrote that you need that amount will be calculated based on qty and rate, but you defined some dataEvents in 'rate' and 'amount' columns instead of 'qty' and 'rate' columns. The next problem that you use editRow method directly inside of gridComplete. So the buttons from the inlineNav toolbar will stay in the wrong status. One more problem is that you need to recompute the 'amount' based on 'qty' and 'rate' not only on the loss of focus from 'qty' and 'rate', but also on saving the values on Enter.
To make solving of above problems easier I wrote the demo which you can modify corresponds your exact requirements. The most important part of the demo you can find below:
var editingRowId = undefined,
recomputeAmount = function () {
var rate = $("#" + editingRowId + "_rate").val(),
qty = $("#" + editingRowId + "_qty").val(),
newAmount = parseFloat(rate) * parseFloat(qty);
$("#" + editingRowId + "_amount").val(isFinite(newAmount) ? newAmount : 0);
},
myEditParam = {
keys: true,
oneditfunc: function (id) {
editingRowId = id;
},
afterrestorefunc: function (id) {
editingRowId = undefined;
},
aftersavefunc: function (id) {
var $this = $(this),
rate = $this.jqGrid("getCell", id, "rate"),
qty = $this.jqGrid("getCell", id, "qty"),
newAmount = parseFloat(rate) * parseFloat(qty);
$this.jqGrid("setCell", id, "amount", newAmount);
editingRowId = undefined;
}
},
numInput = {
type: 'keydown',
fn: function (e) {
var key = e.which;
// allow only '0' <= key <= '9' or key = '.', Enter, Tab, Esc
if ((key < 48 || key > 57) && key !== $.ui.keyCode.PERIOD &&
key !== $.ui.keyCode.TAB && key !== $.ui.keyCode.ENTER && key !== $.ui.keyCode.ESCAPE) {
return false;
}
}
},
recompute = {
type: 'focusout',
fn: function (e) {
recomputeAmount();
}
};
$("#purchasedetailsgrid").jqGrid({
colModel: [
...
{name:'qty', index:'qty',editable:true,width:85,search:false,editrules:{number:true,maxlength:5},
editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [ numInput, recompute ]
}
},
{name:'rate', index:'rate',width:100,editable:true,search:false,editrules:{number:true,maxlength:10},
editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [ numInput, recompute ]
}
},
{name:'amount', index:'amount',width:100,editable:true,search:false,editrules:{number:true,maxlength:10}}
],
loadComplete: function () {
var gridIdSelector = '#' + $.jgrid.jqID(this.id);
if (this.rows.length > 1) {
//$(this).jqGrid('editRow', this.rows[1].id, myEditParam);
$(this).jqGrid('setSelection', this.rows[1].id, true);
setTimeout(function() {
// we should simulate click of the button not after the grid is loaded, but
// after the toolbar with the cliked button will be created by inlineNav
$(gridIdSelector + "_iledit").click();
}, 100);
} else {
setTimeout(function() {
// we should simulate click of the button not after the grid is loaded, but
// after the toolbar with the cliked button will be created by inlineNav
$(gridIdSelector + "_iladd").click();
}, 100);
}
}
});
jQuery("#purchasedetailsgrid").jqGrid('navGrid','#purchasedetailstoolbar',
{view:false,edit:false,add:false,del:false,search: false, refreshtitle: "Reload Grid"});
jQuery("#purchasedetailsgrid").jqGrid('inlineNav','#purchasedetailstoolbar',
{edit: true, add: true, editParams: myEditParam, addParams: {addRowParams: myEditParam}});
If it's needed I can comment unclear parts of the code.

Categories

Resources