Datatables I can't call an onclick event after I paginate? - javascript

I am using http://datatables.net/
The demo table on their homepage resembles pretty much the exact same thing that i'm using (pagination, specifically), except each row has an area to click:
<%= Post.title %>
This link opens a jquery UI modal dialog which displays some information which is ajax requested.
Part 1 (solved), see part 2 below
I'm trying to run an onclick event which works normally on page one, but as soon as i go to page 2 (or any others) it stops working. I checked the source to make sure it wasnt doing anything funny in all the code is infact there (all the rows, even the ones hidden by the pagination)
Any ideas?
$(function() {
$('#dialog').dialog({
autoOpen: false,
resizable: false,
maxHeight: 600,
width: 650,
modal: true,
beforeClose: function close() {
$('#dialog').html('');
}
});
$('.show-post').click(function() {
clickLink(this);
return false;
});
});
Thanks to those who answered my question! I fixed that issue.
Part 2
my next 'issue' id like to get to work is... I'm using the left and right arrow keys to allow them to 'scan' to the next or previous row, and display the information. This is as opposed to closing it and then having to click the next one.
I'd like to make it so when you get to the bottom of page one, or top of page two, hidding next/previous respectively will automatically load that page, go to the top (or bottom), then open that dialog for that row on the other page.
heres my click function (i know its kind of probably not structured the best... im new to jquery)
$(document).ready(function() {
oTable = $('#posts').dataTable({
"bJQueryUI": true,
"iDisplayLength": 400,
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aLengthMenu": [[-1, 400, 100, 50], ["All", 400, 100, 50]]
});
$(this).keydown(function(e) {
var id = $("#dialog").attr("data-id");
currentPost = $("#posts tr[data-id=" + id + "]");
if (e.keyCode == 39 && $('#dialog').html() != "") {
/* Remove current background */
$(currentPost).blur()
$(currentPost).removeClass("current");
$(currentPost).find("td.sorting_1").removeClass("current");
var next = currentPost.next().find(".show-post");
clickLink(next);
} else if (e.keyCode == 37 && $('#dialog').html() != "") {
/* Remove current background */
$(currentPost).removeClass("current");
$(currentPost).find("td.sorting_1").removeClass("current");
var prev = currentPost.prev().find(".show-post");
clickLink(prev)
}
});
});
heres the actual click function
function clickLink(src) {
var post = $(src);
var id = $(post).parent().parent().attr('data-id');
/* Set background for current line */
$(post).parent().parent().find("td.sorting_1").addClass("current");
$(post).parent().parent().addClass("current");
$('#dialog').attr("data-id", id);
$('#dialog').load('/show-post/' + id, function() {
$.ajax({
type: "POST",
url: "/checkstatus/" + id,
dataType: "html",
error: function(data){
$("#dialog").fadeOut("fast", function() {
$("#dialog").html("<img src='/img/invalid.jpg' alt='invalid' style='margin: 40px auto; display: block;'>").fadeIn("slow");
});
}
});
/* Set Visited */
$(post).parent().parent().removeClass("visited").addClass("visited");
$('#dialog').dialog({
title: post.html(),
beforeClose: function close() {
$(post).parent().parent().find("td.sorting_1").removeClass("current");
$(post).parent().parent().removeClass("current");
},
buttons: {
"Email 1": function() {
$.ajax({
type: "POST",
url: "/get-email/" + id + "/" + "1",
dataType: "html",
success: function(data) {
window.location.href = data + "&subject=" + post.html();
}
});
},
}
});
$('#dialog').dialog('open');
});
return false;
};

The example on the link you provided appears to be adding/removing DOM elements, meaning that elements on subsequent pages probably are not in the DOM on page load. Have you tried using event delegation?
$(<root element>).delegate('.show-post', 'click', function() {
clickLink(this);
return false;
});
Where <root element> can be document but should be set to an ancestor element that is always in the DOM.
.delegate():
Attach a handler to one or more events for all elements that match the
selector, now or in the future, based on a specific set of root
elements.
Source: http://api.jquery.com/delegate
UPDATE
Note that .delegate() is an alias of .on() now, so if you're using jQuery 1.7+ I would just use .on() right from the get-go. Almost the same syntax except the selector and event are swapped: $(<root element>).on('click', '.show-post', function() { ... });
Source: Thanks Greg Pettit, Excellent Comment

Below Code is working Perfectly. When you click the pagination button 'drawCallback' class Call some function after table load.
$("#YourTableID").dataTable({
bJQueryUI: false,
bFilter: false,
bSearchable: false,
bInfo: false,
bAutoWidth: false,
bDestroy: true,
"oLanguage": {
"sEmptyTable": "No Records Found"
},
"sPaginationType": "full_numbers",
"bLengthChange": false,
"iDisplayLength": 5,
aaData: arrv,
aoColumns: [{
sTitle: "Select",
orderable: false,
className: 'select-checkbox',
targets: 0
},
{
sTitle: "Course name"
}, {
sTitle: "Level"
}, {
sTitle: "Study Mode"
}, {
sTitle: "Entry Year"
}, {
sTitle: "Point of Entry"
}, {
sTitle: "Awarding qualification"
}],
drawCallback: function () {
//Some function...
},
select: {
style: 'os',
background: 'color:gray',
selector: 'td:first-child'
},
order: [[1, 'asc']],
});

As #scrappedcola pointed out in the comments, your click handler is lost after pagination. There is a drawCallback function for DataTables you can implement which will fire after the table is "re-drawn" (hence drawCallback). Here is an example:
$('#someId').DataTable({
lengthMenu: [ 25, 50, 100, 200 ],
order: [[ 0, 'asc' ]],
processing: true,
serverSide: true,
stateSave: true,
responsive: true,
bDestroy: true,
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
],
drawCallback: function() {
var api = this.api();
api.$('#someBtnId').click(function() {
// do some click handler stuff
});
}
});

Related

editurl:'client array' data to be shown in jqgrid but should not save that data to database

var specificatonsData = [];
function initGridForTransactions(gridID, gridPagerID) {
var grid_selector = gridID;
var pager_selector = gridPagerID;
$(window).on('resize.jqGrid', function () {
$(grid_selector).jqGrid('setGridWidth', $("#page-wrapper").width());
})
var parent_column = $(grid_selector).closest('[class*="col-"]');
$(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
setTimeout(function () {
$(grid_selector).jqGrid('setGridWidth', parent_column.width());
}, 0);
}
})
$(grid_selector).jqGrid({
data: specificatonsData,
datatype: "local",
colNames: ['Id','Specification', 'Abbreviation'],
colModel: [
{ name: 'Id', width: 80,key:true },
{ name: 'specification', index: 'Id', key: true, width: 300 },
{ name: 'abbreviation', width: 300 },
],
cmTemplate: { editable: true },
cellsubmit: 'clientArray',
editurl: 'clientArray',
viewrecords: true,
rowNum: 4000,
gridview: true,
rowList: [4000],
pager: pager_selector,
altRows: true,
loadonce: true,
multiselect: false,
multiboxonly: false,
sortname: 'Specification',
sortorder: "asc",
cellEdit: false,
iconSet: "fontAwesome",
onSelectRow: function (rowId, status, e) {
var dealerFeatures = $("#editor").text();
var selectedFeature = rowId;
selectedFeature = selectedFeature.replace(/(\s+)/, "(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("(" + selectedFeature + ")", "gi");
dealerFeatures = dealerFeatures.replace(pattern, "<mark>$1</mark>");
//dealerFeatures = dealerFeatures.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/, "$1<mark>$2</mark>$4");
dealerFeatures = dealerFeatures.replace(/(<mark>[<>]*)((<[>]+>)+)([<>]*<\/mark>)/, "$1<mark>$2</mark>$4");
dealerFeatures = dealerFeatures.replace(/\n/g, '<br>\n');
$("#editor").html(dealerFeatures);
},
gridComplete: function () {
$(grid_selector).setColProp('Approve', { editoptions: { value: '' } });
},
loadComplete: function () {
var table = this;
setTimeout(function () {
updatePagerIcons(table);
enableTooltips(table);
}, 0);
},
}).navGrid(pager_selector, { edit: true, add: true, del: false },
{
url: '/Activity/SaveSpecification',
closeAfterAdd: true,
closeAfterEdit: true,
afterSubmit: function () {
getAbbrData();
return [true, '', ''];
}
});
jQuery(grid_selector).sortableRows();
function updatePagerIcons(table) {
var replacement =
{
'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
};
$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
})
}
function enableTooltips(table) {
$('.navtable .ui-pg-button').tooltip({ container: 'body' });
$(table).find('.ui-pg-div').tooltip({ container: 'body' });
}
$(document).one('ajaxloadstart.page', function (e) {
$(grid_selector).jqGrid('GridUnload');
$('.ui-jqdialog').remove();
});
}
I will save data to database only when I click on external Submit button.
When I click on edit button the data is showing in a popup and when I click on the save button the data is getting to the database and showing in the jqgrid.
But I have a new requirement where I have to show the data in the jqgrid when click on save button but should not save to the database.
Thanks in advance.
If you use Guriddo jqGrid JS then you can set url in edit options in your navigator to be clientArray - i.e
...navGrid(pager_selector, { edit: true, add: true, del: false },
{
url: 'clientArray',
closeAfterAdd: true,
closeAfterEdit: true,
afterSubmit: function () {
getAbbrData();
return [true, '', ''];
}
});
This will save the data locally.
The code, which you posted contains many small bugs. For example,
you use url: '/Activity/SaveSpecification' as form Edit options (not for Add form) - see navGrid call. You should remove the option to make editurl: 'clientArray' working
you use key:true in more as one column. It's not allowed. One can use it only in one column, which contains unique values.
the usage of index: 'Id' property in colModel for the column name: 'specification' is probably one more bug, which can make wrong sorting and filtering in the column.
your current code contains call of .setColProp('Approve', { ... });, which is wrong, because your colModel don't contains the column 'Approve'
the option sortname: 'Specification' is wrong too, because the value of sortname should be the value of name property from colModel (like sortname: 'specification' for example, if you'll remove index: 'Id' property from the column).
Additionally the usage of rowNum: 4000 can essentially reduce the performance of the grid in case of large grid. If real number of rows is about 4000, then it's much more effective to use local paging of data. The monitor allows to display only about 20-25 rows. Thus it's recommended to use pager with such small rowNum. Users can use paging buttons to go to the next page.

jQuery Datatables prevent scroller reset on table reload

I finally got my datatable to reload on intervals. But what I'm noticing now is if you scrolled to the right, the table reload will reset the scroll back to the left. The same if you are scrolled down, it will reset back to the top.
I need to stop this from happening.
I've tried all the answers from this post: How to maintain jQuery DataTables scroll position after .draw()
Nothing seems to work. Maybe I'm missing something.
I noticed on this post, the question is using a datatables.scroller.min.js: DataTables save state scroll position
This led me to this: https://cdn.datatables.net/scroller/1.4.2/
But there are so many CSS files there. I'm not sure which one to use, if any should be used at all.
Maybe I do not need any of the above, and I just need to adjust my code below to prevent the scroll reset from happening:
Click event:
$('.searchSubmit').on('click', function() {
updateDataTable();
var idle = 0;
var idleInterval = setInterval(timer, 5000);
$(this).mousemove(function(e){idle = 0;});
$(this).keypress(function(e){idle = 0;});
function timer()
{
idle = idle + 1;
if(idle > 2)
{
updateDataTable();
console.log('table reloaded');
}
}
});
Datatable:
function updateDataTable() {
$.ajax({
url: 'api/railmbs.php',
type: 'POST',
data: data,
dataType: 'html',
success: function(data, textStatus, jqXHR)
{
var jsonObject = $.parseJSON(data);
var table = $('#example1').DataTable({
"data": jsonObject,
"columns": [
{ "data": "BILL" },
{ "data": "CONTAINER" },
// few more columns
],
"iDisplayLength": 25,
"paging": true,
"scrollY": 550,
"scrollX": true,
"bDestroy": true,
"stateSave": true,
"autoWidth": true
});
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
}
DOM elements have their current scroll state in elem.scrollLeft/scrollTop,further reading
try this code it rescued me.
var startPos = document.body.scrollLeft
$(selector).DataTable().clear();
$(selector).DataTable().ajax.reload(() => {
document.body.scrollLeft = startPos;
},false);
and for keeping maintaining vertical scroll state try this
var startPos = document.body.scrollTop
$(selector).DataTable().clear();
$(selector).DataTable().ajax.reload(() => {
document.body.scrollTop = startPos;
},false);
Using the DataTable().ajax.reload() will just init the datatable and then make it to reload on a interval (as you're doing currently)
setInterval(function() {
$('#example1').DataTable().ajax.reload(null, false);
}, 5000);
$('#example1').DataTable({
ajax: {
url: "api/railmbs.php",
type: 'POST',
data: data,
dataSrc: function(data) {
return $.parseJSON(data);
}
},
"columns": [{
"data": "BILL"
}, {
"data": "CONTAINER"
},
// few more columns
],
"iDisplayLength": 25,
"paging": true,
"scrollY": 550,
"scrollX": true,
"bDestroy": true,
"stateSave": true,
"autoWidth": true
});
As per DataTables Documents resetPaging (the second parameter on false)
Reset (default action or true) or hold the current paging position
(false). A full re-sort and re-filter is performed when this method is
called, which is why the pagination reset is the default action.
This means that neither the pagination(None than it matters if you have scrollY) nor the position of the scroll (X or Y) should reset.

jqGrid inline editing not working after adding new row

I'm currently using free-jqGrid version 4.14.1 (using cdn hyperlink). I would like to let the users add a new row with their input values, and edit the row if they want to make any change by clicking the row. For adding new row, I created an adding button (not using jqGrid pager).
I'm now facing two different issues:
1) I refered this demo for inline editting. According to this demo code, I need to use the line
grid.jqGrid('restoreRow', lastSelection);
However, with this line, everytime I am adding new row, the previous row is deleted and only newly added row is displayed. Please check this fiddle.
2) Due to 1), I commented out that line(I don't think I supposed to do that for proper functioning), and tried to run. The previously added rows remain after adding new row, but all rows displayed is showing in textbox like this(fiddle):
What I would like to have is only after user clicks the row to modify, it changes to the textboxes like the guriddo demo.
I have not found any post related to this issues. Is there anyone please help me??
============================================
Add:
I started with some base table value just for verification. The base data rows were functioning as I wanted (click the row for modification), but the new rows were not. It seems like new rows are not selected and not focused when I click, and not exiting the edit mode after hitting enter key..
============================================
============================================
The below is the code of grid just for reference:
$(document).ready(function () {
Load_Bin();
$('#Bin-QtyBin').focus();
$('#btnEnter-Bin').click(function () {
var valNumBin = $('#Bin-numBin').val();
//if bins are dropbox: select enabled one
var valQtyBin = $('#Bin-QtyBin').val();
var paramRow = {
rowId: "new_row",
initdata: {
numBin: valNumBin,
QtyPutAway: valQtyBin
},
position: "first" //"last"
}
$("#tbBin").jqGrid('addRow', paramRow);
$('#Bin-numBin').val('');
$('#Bin-QtyBin').val('');
});
});
var lastSelection;
function Load_Bin() {
var tbBinArea = $('#tbBin');
tbBinArea.jqGrid({
datatype: "local",
colModel: [
{ label: 'Bin', name: 'numBin', sorttype: 'text', searchoptions: { clearSearch: true }, width: 310, editable: true },
{ label: 'Put Away Qty.', name: 'QtyPutAway', sorttype: 'number', searchoptions: { clearSearch: true }, width: 310, editable: true }],
rowNum: 10,
rowList: [10, 15, 30, "10000:All"],
prmNames: {
page: 'defaultPageNumber',
rows: 'rowsPerPage'
},
//forceClientSorting: true,
rownumbers: true,
//autowidth: true,
viewrecords: true,
loadonce: true,
multiselect: false,
multiPageSelection: false,
iconSet: "fontAwesome",
pager: true,
height: 250,
onSelectRow: editRow,
searching: {
searchOperators: true,
defaultSearch: 'cn',
closeOnEscape: true,
searchOnEnter: false,
multipleSearch: true
}
});
}
function editRow(id) {
if (id && id !== lastSelection) {
var grid = $("#tbBin");
grid.jqGrid('restoreRow', lastSelection);
grid.jqGrid('editRow', id, { keys: true });
lastSelection = id;
}
};
(p.s. thanks to the owner of this fiddle since I was struggling to move the code to fiddle, and sorry for not addressing him/her since I lost the original answer link for that fiddle... )
I ended up just reload the whole grid after adding new row. It works fine, except that newly added line does not turn to edit mode since it doesn't detect whether user clicks it or not since it is already highlighted when it was created..
After creating new row, just added this code:
var reloaddata = $('#tbBin').jqGrid("getGridParam", "data");
$('#tbBin')
.jqGrid('setGridParam',
{
datatype: 'local',
data: reloaddata
})
.trigger("reloadGrid");

Magnific popup does not work on second page of Datatables

I have created a datatables and add an image column into datatables. When i click image, i would like to image open at popup. It is work on for first page of datatable, however when i passed to second page, it doesn't work. Also i put alert() to test second page event and alert() works, but popup does not.
Please check my snippets: https://jsfiddle.net/f08qdeq2/20/
How can i solve this problem, any ideas? Thank You
$(document).ready(function() {
var table = $('#datatable').dataTable({
aLengthMenu: [
[1, 2],
[1, 2]
],
iDisplayLength: 1
});
});
$(this.document).ready(function() {
$('.image-popup').magnificPopup({
type: 'image',
closeOnContentClick: true,
closeBtnInside: false,
fixedContentPos: true,
image: {
verticalFit: true
},
zoom: {
enabled: true,
duration: 300 // don't foget to change the duration also in CSS
},
});
});
$(document).on('click', '.image-popup', function() {
alert('You Clicked Image');
//$('.image-popup-no-margins').magnificPopup({
//Some Working code here
//});
})
You should use fnDrawCallback for initialize your popup. try this...
$(document).ready(function() {
var table = $('#datatable').dataTable({
aLengthMenu: [
[1, 2],
[1, 2]
],
iDisplayLength: 1,
"fnDrawCallback": function () {
$('.image-popup').magnificPopup({
type: 'image',
closeOnContentClick: true,
closeBtnInside: false,
fixedContentPos: true,
image: {
verticalFit: true
},
zoom: {
enabled: true,
duration: 300 // don't foget to change the duration also in CSS
},
});
}
});
});
$(document).on('click', '.image-popup', function() {
alert('You Clicked Image');
})
Result : https://jsfiddle.net/cmedina/f08qdeq2/21/
just adding this will work for normal click event, based on this you can do anything with model(pop-up).
$(document).on('click', '.image-popup', function() {
alert('You Clicked Image');
})

Enabling Save button on JQ Grid with InlineEditing and CellEdit

Hi I have a Grid that is using cell edit and Inline editing. It saves to the ClientArray
$('#list').jqGrid({
datatype: "local",
colNames: ["Parameter Id", "Parameter Name", 'Parameter Value'],
colModel: [
{ name: "Id", index: "Id", align: "left", key: true, editable: false,hidden:true, jmap: 0 },
{ name: "ParameterName", index: "ParameterName", align: "left", editable: false, jmap: 1 },
{ name: "ParameterValue", index: "ParameterValue", align: "left", editable: true, edittype: "text", editoptions: { maxlength: 100 }, editrules: {required: true }, jmap: 2 }
],
pager: "#pager",
rowNum: 100,
rowList: [],
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'
height: '100%',
scrollOffset: 0,
sortname: "Name",
sortorder: "Asc",
gridview: true,
caption: 'Parameters',
autowidth: true,
hidegrid: false,
loadonce: true,
//beforeEditCell: function () {
// $("#list_ilsave").removeClass('ui-state-disabled');
// return;
//},
//afterEditCell: function (rowid, cellname, value, iRow, iCol) {
// $('#list').jqGrid('getCell', rowid, iCol).focus();
// return;
//},
width: totalWidth,
cellEdit: true,
cellsubmit: "clientArray"
});
$('#list').jqGrid('inlineNav', '#pager', {
edit: false,
add: false,
del: false,
save: true,
savetext: 'Save',
cancel: false
});
When I edit a Cell the save button remains disabled. If I manually Enable the button in beforeCellEdit, the editable cell hasn't got focus until you select another cell. This behavior is only happening in IE.
I have tried to fix both these issues individually in my commented out code, and I have found that the loss of focus is caused by the line
$("#list_ilsave").removeClass('ui-state-disabled');
I tried placing this line in beforeEditCell and in afterEditCell and it causes the input field to loose focus.
I was using JQ Grid 4.4.4 and I have tried updating to 4.6.0 after I read there were updates to Inline Editing after 4.4.4
UPDATE
I have changed my grid to use onSelectRow
onSelectRow: function (rowid) {
var $grid = $('#list');
var iRow = $("#" + rowid)[0].rowIndex;
$grid.jqGrid('editRow', rowid, {
keys: true,
oneditfunc: function(rowid, response) {
var $saveButton = $("#list_ilsave");
if ($saveButton.hasClass('ui-state-disabled')) {
$saveButton.removeClass('ui-state-disabled');
}
markCellAsDirty(rowid, $grid);
return true;
},
successfunc: function() {
alert('success');
return true;
},
aftersavefunc: function() {
alert('after save');
return true;
},
errorfunc: function() {
alert('error');
return true;
}
});
},
cellsubmit: "clientArray"
But I can't get any of the editRow events to fire other than oneditfunc. I also have an issue with getting the changed cells.
This method marks the cells as dirty / edited
function markCellAsDirty(rowid, grid) {
$(grid.jqGrid("setCell", rowid, "ParameterValue", "", "dirty-cell"));
$(grid[0].rows.namedItem(rowid)).addClass("edited");
}
I try to get the edited cells as follows
var editedRows = $grid.getChangedCells('dirty');
Before posting editedRows in an AJAX method to my server.
I'm not sure what you want to implement exactly, but I modified your demo to the following https://jsfiddle.net/OlegKi/byygepy3/11/. I include the full JavaScript code of the demo below
$(function () {
var myData = [
{ id: 10, ParameterName: "Test", ParameterValue: "" },
{ id: 20, ParameterName: "Test 1", ParameterValue: "" },
{ id: 30, 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) {
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++) {
if (savedRows[i].id !== rowid) {
// save currently editing row
// one can replace saveRow to restoreRow in the next line
$self.jqGrid("saveRow", savedRows[i].id);
}
}
return savedRows.length === 0; // 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: true,
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 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");
});
where HTML code is
<div class="container-fluid">
<div class="row">
<div id="gridarea" class="col-md-6 col-md-offset-3">
<table id="list"></table>
</div>
</div>
</div>
and CSS code
.ui-th-column>div, .ui-jqgrid-btable .jqgrow>td {
word-wrap: break-word; /* IE 5.5+ and CSS3 */
white-space: pre-wrap; /* CSS3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
overflow: hidden;
vertical-align: middle;
}
It demonstrate how one can implement starting inline editing on select row. Additionally I added optional column with template: "actions" which can be alternative implementation. I set property dirty in every item of data inside of afterSetRow callback and I added "Save Changed" button, which uses localData = $(this).jqGrid("getGridParam", "data") and dirtyData = $.grep(localData, function (item) { return item.dirty; }); to get the dirty (modified) data.

Categories