how do i assign value to columns in jqGird? - javascript

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.

Related

Datatable custom filtering with Server Side with Editor

I am having some trouble integrating some custom functionalities with Datatable and Datatable Editor at the same time.
Without server-side processing my current functionalities works perfectly but I want to be able to implement server-side filtering with Editor.
With server-side filtering these work:
1.Pagination
2.Global Search
3.Sorting
4.Row reorder
5.Dynamic Page length
With server-side filtering these don't work:
1.Custom column input filtering
2.Custom footer select filtering
My serverside script for Datatable and Editor:
Editor::inst($db, 'article_categories')
->fields(
Field::inst('article_categories.id')->validator('Validate::numeric'),
Field::inst('article_categories.name')->validator('Validate::notEmpty'),
Field::inst('article_categories.description'),
Field::inst('article_categories.rowOrder')->validator('Validate::numeric')
)
->on('preCreate', function ($editor, $values) {
if (!$values['article_categories']['rowOrder']) {
$next = $editor->db()->sql('select IFNULL(MAX(rowOrder)+1, 1) as next FROM article_categories')->fetch();
$editor->field('article_categories.rowOrder')->setValue($next['next']);
} else {
$editor->db()
->query('update', 'article_categories')
->set('rowOrder', 'rowOrder+1', false)
->where('rowOrder', $values['article_categories']['rowOrder'], '>=')
->exec();
}
})
->on('preRemove', function ($editor, $id, $values) {
$order = $editor->db()
->select('article_categories', 'rowOrder', array('id' => $id))
->fetch();
$editor->db()
->query('update', 'article_categories')
->set('rowOrder', 'rowOrder-1', false)
->where('rowOrder', $order['rowOrder'], '>')
->exec();
})
->process($request->all())
->json();
My client-side script:
Default config:
jQuery(function () {
$.extend(true, $.fn.dataTable.defaults, {
serverSide: true,
fixedHeader: true,
searchDelay: 800,
paging: true,
processing: true,
pageLength: 10,
info: true,
dom: "Blfrtip",
select: true,
responsive: true,
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
});
});
Datatable and Editor setup:
var editor;
jQuery(function () {
//Editor
editor = new $.fn.dataTable.Editor({
table: "#article-category",
ajax: {
url: "article-categories",
type: "POST",
},
fields: [
{
label: "Order:",
name: "article_categories.rowOrder",
type: "hidden",
fieldInfo:
"This field can only be edited via click and drag row reordering.",
},
{
label: "FAQ Category Name:",
name: "article_categories.name",
},
{
label: "Description (optional):",
name: "article_categories.description",
type: "textarea",
},
],
});
//Datatable
var table = $("#article-category").DataTable({
ajax: {
url: "article-categories",
type: "POST",
},
rowReorder: {
dataSrc: "article_categories.rowOrder",
editor: editor,
},
buttons: cms.editorFormButtons(editor),
initComplete: function () {
cms.headerInputFilter("article-category", this.api(), [1, 2]);
cms.footerSelectFilter(this.api(), [1, 2]);
},
columns: [
{
data: "article_categories.rowOrder",
name: "article_categories.rowOrder",
className: "reorder no-inline",
},
{
data: "article_categories.name",
name: "article_categories.name",
},
{
data: "article_categories.description",
name: "article_categories.description",
},
],
});
//Inline Editor
cms.inlineEdit("article-category", editor);
editor
.on("postCreate postRemove", function () {
table.ajax.reload(null, false);
})
.on("initCreate", function () {
editor.field("article_categories.rowOrder").enable();
})
.on("initEdit", function () {
editor.field("article_categories.rowOrder").disable();
});
});
Custom functions:
let footerSelectFilter = function (table, columns) {
if (typeof columns != "undefined" && typeof table != "undefined") {
table.columns(columns).every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on("change", function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column
.search(val ? "^" + val + "$" : "", true, false)
.draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append(
'<option value="' + d + '">' + d + "</option>"
);
});
});
}
};
let headerInputFilter = function (target, table, searchableColumns) {
if (
typeof searchableColumns != "undefined" &&
typeof target != "undefined" &&
typeof table != "undefined"
) {
$("#" + target + " thead tr")
.clone(true)
.addClass("filters")
.appendTo("#" + target + " thead");
var i = 0;
var api = table;
api.columns()
.eq(0)
.each(function (colIdx) {
if (
searchableColumns.includes(
$(api.column(colIdx).header()).index()
)
) {
var cell = $(".filters th").eq(
$(api.column(colIdx).header()).index()
);
var title = $(cell).text();
$(cell).html(
'<input style="width:100% !important" type="text" placeholder="' +
title +
'" />'
);
$(
"input",
$(".filters th").eq(
$(api.column(colIdx).header()).index()
)
)
.off("keyup change")
.on("keyup change", function (e) {
e.stopPropagation();
$(this).attr("title", $(this).val());
var regexr = "({search})";
var cursorPosition = this.selectionStart;
api.column(colIdx)
.search(
this.value != ""
? regexr.replace(
"{search}",
"(((" + this.value + ")))"
)
: "",
this.value != "",
this.value == ""
)
.draw();
$(this)
.focus()[0]
.setSelectionRange(
cursorPosition,
cursorPosition
);
});
} else {
return true;
}
});
}
};
let editorFormButtons = function (editor) {
if (typeof editor != "undefined") {
return [
{
extend: "create",
editor: editor,
formButtons: [
{
label: "Save",
fn: function () {
var that = this;
this.submit(function () {
that.close();
});
},
},
],
},
{
extend: "edit",
text: "Edit",
editor: editor,
formButtons: [
{
label: "Save & close",
fn: function () {
var that = this;
this.submit(function () {
that.close();
});
},
},
{
label: "Update",
fn: function () {
this.submit(function () {
editor.edit(
table.rows({ selected: true }).indexes()
);
});
},
},
],
},
{
extend: "remove",
editor: editor,
formButtons: [
{
label: "Delete",
fn: function () {
var that = this;
this.submit(function () {
that.close();
});
},
},
],
},
];
}
};
let inlineEdit = function (target, editor) {
if (typeof target != "undefined" && typeof editor != "undefined") {
$("#" + target + "").on(
"click",
"tbody td:not(.no-inline)",
function (e) {
if (
$(this).hasClass("editor-edit") ||
$(this).hasClass("control") ||
$(this).hasClass("select-checkbox") ||
$(this).hasClass("dataTables_empty")
) {
return;
}
editor.inline(this, {
submit: "allIfChanged",
});
}
);
}
};
module.exports = {
headerInputFilter,
footerSelectFilter,
editorFormButtons,
inlineEdit,
};
When I set server-side to false the custom functionalities I need works perfectly but I need these with server-side processing as it will significantly improve overall performance . I would appreciate any help and suggestion.
Regards,
Shovon Choudhury

How do I select only the filtered rows in jQgrid?

I have a grid (made with jqGrid 4.15.2). The code looks like the one below:
$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
$(function () {
"use strict";
var $grid = $("#list"),
maximizeGrid = function () {
var newWidth = $grid.closest(".ui-jqgrid").parent().width();
$grid.jqGrid("setGridWidth", newWidth, true);
};
// Resize grid if window is being resized
$(window).on("resize", maximizeGrid);
$grid.jqGrid({
colNames: ["", "Form #", "Form", "Plan", "Class", "Drug"],
colModel: [
{name: "act", template: "actions"},
{
name: "FormId",
align: 'center',
fixed: true,
frozen: true,
resizable: false,
width: 100,
editable: "hidden"
},
{name: "FormName", search: true, stype: "text"},
{name: "PlanName", search: true, stype: "text"},
{
name: "DrugGroupName",
edittype: "select",
editable: true,
search: true,
editoptions: {
dataUrl: "/ajax/drug_groups/get_all",
buildSelect: function (data) {
var select = "<select>", i;
for (i = 0; i < data.length; i++) {
select += "<option value='" + String(data[i].Id) + "'>" + $.jgrid.htmlEncode(data[i].DrugGroupName) + "</option>"
}
return select + "</select>";
},
selectFilled: function (options) {
setTimeout(function () {
$(options.elem).select2({
width: "100%"
});
}, 0);
}
},
stype: "select", searchoptions: {
sopt: ["eq", "ne"],
generateValue: true,
noFilterText: "Any",
selectFilled: function (options) {
setTimeout(function () {
$(options.elem).select2({
width: "100%"
});
}, 0);
}
}
},
{name: "DrugName", search: true, stype: "text"}
],
cmTemplate: {
width: 300,
autoResizable: true
},
iconSet: "fontAwesome",
rowNum: 25,
guiStyle: "bootstrap",
autoResizing: {
compact: true,
resetWidthOrg: true
},
rowList: [25, 50, 100, "10000:All"],
toolbar: [true, "top"],
viewrecords: true,
autoencode: true,
sortable: true,
pager: true,
toppager: true,
cloneToTop: true,
hoverrows: true,
multiselect: true,
multiPageSelection: true,
rownumbers: true,
sortname: "Id",
sortorder: "desc",
loadonce: true,
autowidth: true,
autoresizeOnLoad: true,
forceClientSorting: true,
prmNames: {id: "Id"},
jsonReader: {id: "Id"},
url: '/ajax/plans_to_forms/get_all',
datatype: "json",
editurl: '/ajax/plans_to_forms/update',
formDeleting: {
url: '/ajax/plans_to_forms/delete/',
delicon: [true, "left", "fa-scissors"],
cancelicon: [true, "left", "fa-times"],
width: 320,
caption: 'Delete Plan to Form Link',
msg: 'Are you sure you want to delete this link?',
beforeShowForm: function ($form) {
var rowids = $form.find("#DelData>td").data("rowids");
$form.closest(".ui-jqdialog").position({
of: window,
my: "center center",
at: "center center"
});
if (rowids.length > 1) {
$form.find("td.delmsg").html('Are you sure you want to delete all the selected form links?');
}
},
afterComplete: function (response, postdata, formid) {
if (response.responseText === "true") {
toastr["success"]("The link was deleted successfully.", "Information");
} else {
toastr["error"]("Something went wrong, the link could not be deleted.", "Error");
}
}
},
ajaxSelectOptions: {
type: "POST",
dataType: "json"
},
navOptions: {
edit: false,
add: false,
search: false
},
inlineEditing: {
keys: true,
focusField: "DrugGroupName",
serializeSaveData: function (postData) {
var changedData = {}, prop, p = $(this).jqGrid("getGridParam"),
idname = p.keyName || p.prmNames.id,
oldValue, cm;
for (prop in postData) {
oldValue = p.savedRow[0][prop];
if (p.iColByName[prop] != null) {
cm = p.colModel[p.iColByName[prop]];
}
if (postData.hasOwnProperty(prop) && (postData[prop] !== oldValue || prop === idname)) {
changedData[prop] = postData[prop];
}
}
return changedData;
},
aftersavefunc: function () {
toastr["success"]("The record was updated successfully.", "Information");
},
errorfunc: function () {
toastr["error"]("Something went wrong, the record could not be updated.", "Error");
}
},
onSelectRow: function (rowid, status, e) {
var $self = $(this),
$td = $(e.target).closest("tr.jqgrow>td"),
p = $self.jqGrid("getGridParam"),
savedRow = p.savedRow;
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
if ($td.length > 0 && $td[0].cellIndex !== p.iColByName.act) {
// don't start editing mode on click on "act" column
$self.jqGrid("editRow", rowid);
}
},
loadComplete: function () {
var $self = $(this), p = $self.jqGrid("getGridParam");
if (p.datatype === "json") {
// recreate the toolbar because we use generateValue: true option in the toolbar
$self.jqGrid("destroyFilterToolbar").jqGrid("filterToolbar");
}
}
}).jqGrid('navGrid').jqGrid("filterToolbar").jqGrid('setFrozenColumns');
// fill top toolbar
$('#t_' + $.jgrid.jqID($grid[0].id)).append($("<div><label for=\"globalSearchText\">Global search in grid for: </label><input id=\"globalSearchText\" type=\"text\"></input> <button id=\"globalSearch\" type=\"button\">Search</button></div>"));
$("#globalSearchText").keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
if (key === $.ui.keyCode.ENTER) { // 13
$("#globalSearch").click();
}
});
$("#globalSearch").button({
icons: {primary: "ui-icon-search"},
text: false
}).click(function () {
var postData = $grid.jqGrid("getGridParam", "postData"),
colModel = $grid.jqGrid("getGridParam", "colModel"),
rules = [],
searchText = $("#globalSearchText").val(),
l = colModel.length,
i,
cm;
for (i = 0; i < l; i++) {
cm = colModel[i];
if (cm.search !== false && (cm.stype === undefined || cm.stype === "text")) {
rules.push({
field: cm.name,
op: "cn",
data: searchText
});
}
}
postData.filters = JSON.stringify({
groupOp: "OR",
rules: rules
});
$grid.jqGrid("setGridParam", {search: true});
$grid.trigger("reloadGrid", [{page: 1, current: true}]);
return false;
});
});
When I filter something and then want to mark the filtered results for delete all of them for some reason everything gets selected even those that hasn't been filtered which is sending all the IDs to the backend and therefore I am loosing everything when deleting based on the ID.
Maybe it's an stupid option or something else but I can't find what is wrong. Here is a video I have made showing up the issue. Here is a Fiddle for play with where you can see the issue happening
Steps to reproduce the issue:
Filter the column Filename by test
Using the first checkbox mark all of them
Without un-mark anything, remove the filter
Result: everything has been selected and therefore will be posted
Any ideas? Any help?
I find the problem, which you describe, very interesting and thus I changed the default behavior of "Select All" button (checkbox) to select only currently filtered data (see the commit). The new option selectAllMode with the value "all" allows to have the old behavior.
Your demo uses the latest free jqGrid directly from GitHub and thus it should work already like you want.

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/

Filter toolbar not coming in jqGrid

I am using free jqGrid 4.14. I am having trouble in displaying filter toolbar in the grid. I am using the same code that I was using to display filter toolbar in version 4.1.2
but here the toolbar is not appearing.
I need the toolbar to display only when filter image is clicked in the grid otherwise it should hide. So, I am using the below code for that in previous version but here in new the same is
not working
grid.jqGrid({
datatype: "jsonstring",
datastr: grid_data,
colNames: scopes.grid_header_column_value,
colModel: scopes.gridcolumns,
height: height,
viewrecords: is_pager_enable,
multiSort: true,
ignoreCase: true,
grouping: is_group_enable,
sortorder: sort_order,
sortable: false,
pager: "#" + pager_id,
treeGrid: true,
treeGridModel: 'adjacency',
treedatatype: "local",
ExpandColumn: 'name',
gridComplete: function () {
$("#" + grid_id+"count").html($("#" + grid_id).getGridParam('records')+" row(s)");
},
beforeSelectRow: function (rowid, e) {
var item = $(this).jqGrid("getLocalRow", rowid);
if (item != null && item.isLeaf) {
$("#"+$rootScope.subpopup).css("display", "block");
$scope.getPopup($rootScope.xmlname,grid_id,rowid);
}
return true; // allow row selection
},
loadComplete: function () {
var ts = this;
//document.querySelector('#filterbutton').addEventListener('onclick', clickqw);
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
}
});
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn", searchOperators: true }).navGrid("#" + pager_id, { edit: false, add: false, del: false, refresh: true, search: false });
Here I am hiding or showing the bar on need basis
var count = 1;
grid.closest("div.ui-jqgrid-view").find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-jqgrid-labels > th.ui-th-column > div.ui-jqgrid-sortable > button.btnfilter ")
.each(function () {
$('<button>').css({ height: '10px',background: 'url(img/filter.png) no-repeat',border: '0'
}).appendTo(this).button({
icons: {
primary: ""
},
text: false
}).click(function (e) {
var idPrefix = "jqgh_" + grid[0].id + "_",
thId = $(e.target).closest('div.ui-jqgrid-sortable')[0].id;
if (thId.substr(0, idPrefix.length) === idPrefix) {
if (count == 1) {
$('#gview_' + grid_id).find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-search-toolbar").show();
count = 0;
}
else {
$('#gview_' + grid_id).find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-search-toolbar").hide();
count = 1;
}
return false;
}
});
});
$('#gview_' + grid_id).find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-search-toolbar").hide();
EDIT : Adding the images
This is when image where there the filter is not applied. Only the image (funnel image) for filter where the filter can be applied is shown.
Here when we click on the image of filter only then the filtertoolbar should appear.

jquery datatable - applying value for select.className is not working as expected

I am trying to change the background color of selected row(s) in jquery datatable using my own css class but, the tick mark in the checkbox is not appearing.
If I remove className: 'selected-row' from the below code, then everything works normal but, without the color I want.
Fiddler: https://jsfiddle.net/8f63kmeo/12/
HTML:
<table id="CustomFilterOnTop" class="table table-bordered table-condensed" width="100%"></table>
JS
var Report4Component = (function () {
function Report4Component() {
//contorls
this.customFilterOnTopControl = "CustomFilterOnTop"; //table id
//data table object
this.customFilterOnTopGrid = null;
//variables
this.result = null;
}
Report4Component.prototype.ShowGrid = function () {
var instance = this;
//create the datatable object
instance.customFilterOnTopGrid = $('#' + instance.customFilterOnTopControl).DataTable({
columns: [
{ title: "<input name='SelectOrDeselect' value='1' id='ChkBoxSelectAllOrDeselect' type='checkbox'/>" },
{ data: "Description", title: "Desc" },
{ data: "Status", title: "Status" },
{ data: "Count", title: "Count" }
],
"paging": true,
scrollCollapse: true,
"scrollX": true,
scrollY: "300px",
deferRender: true,
scroller: true,
dom: '<"top"Bf<"clear">>rt <"bottom"<"Notes">i<"clear">>',
buttons: [
{
text: 'Load All',
action: function (e, dt, node, config) {
instance.ShowData(10000);
}
}
],
columnDefs: [{
orderable: false,
className: 'select-checkbox text-center',
targets: 0,
render: function (data, type, row) {
return '';
}
}],
select: {
style: 'multi',
selector: 'td:first-child',
className: 'selected-row'
}
});
};
Report4Component.prototype.ShowData = function (limit) {
if (limit === void 0) { limit = 100; }
var instance = this;
instance.customFilterOnTopGrid.clear(); //latest api function
instance.result = instance.GetData(limit);
instance.customFilterOnTopGrid.rows.add(instance.result.RecordList);
instance.customFilterOnTopGrid.draw();
};
Report4Component.prototype.GetData = function (limit) {
//structure of the response from controller method
var resultObj = {};
resultObj.Total = 0;
resultObj.RecordList = [];
for (var i = 1; i <= limit; i++) {
resultObj.Total += i;
var record = {};
record.Description = "This is a test description of record " + i;
record.Status = ["A", "B", "C", "D"][Math.floor(Math.random() * 4)] + 'name text ' + i;
record.Count = i;
resultObj.RecordList.push(record);
}
return resultObj;
};
return Report4Component;
}());
$(function () {
var report4Component = new Report4Component();
report4Component.ShowGrid();
report4Component.ShowData();
});
function StopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
}
Issue:
Any suggestion / help will be greatly appreciated.
It's the class selected that sets the checkbox tick etc. and by using a different class the selected class is no longer added.
You can just add both those classes instead, and it should work
select: {
style: 'multi',
selector: 'td:first-child',
className: 'selected-row selected'
}
FIDDLE

Categories

Resources