Disable Next/Last Pager in jqgrid - jqgrid

I'm using jqGrid in which the Next/Last pager is enabled even when there is no records in the jqgrid during a filter condition is applied.
I have a demo of #Oleg, in which first select "5" in the number of rows displayed in the pager. Then filter the grid in which it shows no records. Now you can see the Next/Last pager button still enabled while the Previous/first is disabled.
I need to disable the First/Previous, Next/Last and the rowList(5,10,20,50).
I'm using the datatype:local but i dont use loadonce:true.
Here is the Demo

I suppose that you use datatype: "local" or datatype: "json" or datatype: "xml" together with loadonce: true. In the case I would recommend you to add the following localReader:
localReader: {
page: function (obj) {
if (obj.rows == null || obj.rows.length === 0) {
return "0";
}
}
}
It should fix the problem with enabled Next and Last buttons in the pager.

Debugging the code i found this, Modifying the code of #Oleg.
This works fine for me:
localReader: {
page: function (obj) {
if (obj.rows == null || obj.rows.length === 0) {
return "0";
}
}
}
The else part gets the row count of the page and bind it to the pager. So the grid gets collapsed.
Thanks #Oleg for your answer.

Related

JQGrid - toggling multiselect

Is there a way to toggle the multiselect option of a grid?
Changing the multiselect parameter of the grid and calling for a reload has the side-effect of leaving the header behind when disabling or not creating the header column if multiselect was not TRUE upon the grid creation.
The closest I have come is setting multiselect to TRUE upon grid creation and using showCol and hideCol to toggle: $('#grid').showCol("cb").trigger('reloadGrid');
This has a side effect of changing the grid width when toggled. It appears the cb column width is reserved when it is not hidden.
Basically I'm attempting to create a grid with an "edit/cancel" button to toggle the multiselect -- very similar to how the iPhone/iPad handles deleting multiple mail or text messages.
Thank you in advance.
I full agree with Justin that jqGrid don't support toggling of multiselect parameter dynamically. So +1 to his answer in any way. I agree, that the simplest and the only supported way to toggle multiselect parameter will be connected with re-initialize (re-creating) the grid.
So if you need to change the value of multiselect parameter of jqGrid you need first change multiselect parameter with respect of respect setGridParam and then re-creating the grid with respect of GridUnload method for example. See the demo from the answer.
Nevertheless I find your question very interesting (+1 for you too). It's a little sport task at least to try to implement the behavior.
Some remarks for the understanding the complexity of the problem. During filling of the body of the grid jqGrid code calculate positions of the cells based on the value of multiselect parameter (see setting of gi value here and usage it later, here for example). So if you will hide the column 'cb', which hold the checkboxes, the cell position will be calculated wrong. The grid will be filled correctly only if either the column 'cb' not exists at all or if you have multiselect: true. So you have to set multiselect: true before paging or sorting of the grid if the column 'cb' exist in the grid. Even for hidden column 'cb' you have to set multiselect to true. On the other side you have to set multiselect to the value which corresponds the real behavior which you need directly after filling of the grid (for example in the loadComplete).
I hope I express me clear inspite of my bad English. To be sure that all understand me correctly I repeat the same one more time. If you want try to toggle multiselect dynamically you have to do the following steps:
create grid in any way with multiselect: true to have 'cb' column
set multiselect: false and hide 'cb' column in the loadComplete if you want to have single select behavior
set multiselect: true always before refreshing the grid: before paging, sorting, filtering, reloading and so on.
I created the demo which seems to work. It has the button which can be used to toggle multiselect parameter:
In the demo I used the trick with subclassing (overwriting of the original event handle) of reloadGrid event which I described the old answer.
The most important parts of the code from the demo you will find below:
var events, originalReloadGrid, $grid = $("#list"), multiselect = false,
enableMultiselect = function (isEnable) {
$(this).jqGrid('setGridParam', {multiselect: (isEnable ? true : false)});
};
$grid.jqGrid({
// ... some parameters
multiselect: true,
onPaging: function () {
enableMultiselect.call(this, true);
},
onSortCol: function () {
enableMultiselect.call(this, true);
},
loadComplete: function () {
if (!multiselect) {
$(this).jqGrid('hideCol', 'cb');
} else {
$(this).jqGrid('showCol', 'cb');
}
enableMultiselect.call(this, multiselect);
}
});
$grid.jqGrid('navGrid', '#pager', {add: false, edit: false, del: false}, {}, {}, {},
{multipleSearch: true, multipleGroup: true, closeOnEscape: true, showQuery: true, closeAfterSearch: true});
events = $grid.data("events"); // read all events bound to
// Verify that one reloadGrid event hanler is set. It should be set
if (events && events.reloadGrid && events.reloadGrid.length === 1) {
originalReloadGrid = events.reloadGrid[0].handler; // save old
$grid.unbind('reloadGrid');
$grid.bind('reloadGrid', function (e, opts) {
enableMultiselect.call(this, true);
originalReloadGrid.call(this, e, opts);
});
}
$("#multi").button().click(function () {
var $this = $(this);
multiselect = $this.is(":checked");
$this.button("option", "label", multiselect ?
"To use single select click here" :
"To use multiselect click here");
enableMultiselect.call($grid[0], true);
$grid.trigger("reloadGrid");
});
UPDATED: In case of usage jQuery in version 1.8 or higher one have to change the line events = $grid.data("events"); to events = $._data($grid[0], "events");. One can find the modified demo here.
I really like what you are trying to do here, and think it would be a great enhancement for jqGrid, but unfortunately this is not officially supported. In the jqGrid documentation under Documentation | Options | multiselect you can see the Can be changed? column for multiselect reads:
No. see HOWTO
It would be nice if there was a link or more information about that HOWTO. Anyway, this is probably why you are running into all of the weird behavior. You may be able to work around it if you try hard enough - if so, please consider posting your solution here.
Alternatively, perhaps you could re-initialize the grid in place and change it from/to a multi-select grid? Not an ideal solution because the user will have to wait longer for the grid to be set up, but this is probably the quickest solution.
A simpler answer:
<input type="button" value="Multiselect" onclick="toggle_multiselect()">
<script>
function toggle_multiselect()
{
if ($('#list1 .cbox:visible').length > 0)
{
$('#list1').jqGrid('hideCol', 'cb');
jQuery('.jqgrow').click(function(){ jQuery('#list1').jqGrid('resetSelection'); this.checked = true; });
}
else
{
$('#list1').jqGrid('showCol', 'cb');
jQuery('.jqgrow').unbind('click');
}
}
</script>
Where list1 is from <table id="list1"></table>.

How to delete rows with local data in jqgrid

jqGrid parameter loadonce: true is used
Selecting rows and pressing delete button
No url is set
How to delete rows in local data only and suppress this error message ?
Is it possbile to set some dummy url or any other idea to allow row delete?
It would be nice if add and edit forms can be used also with local data.
url: 'GetData',
datatype: "json",
multiselect: true,
multiboxonly: true,
scrollingRows : true,
autoencode: true,
loadonce: true,
prmNames: {id:"_rowid", oper: "_oper" },
rowTotal: 999999999,
rownumbers: true,
rowNum: 999999999,
Update 1
From Oleg answer I understood the following solution:
Disable jqGrid standard delete button
Add new delete button to toolbar.
From this button click event call provided
grid.jqGrid('delGridRow', rowid, myDelOptions);
method.
Multiple rows can selected. How to delete all selected rows, this sample deletes only one ?
Is'nt it better to change jqGrid so that delete, edit, add buttons work without url ? Currently it is required to pass dummy url which returns success always for local data editing.
You can use delRowData method do delete any local row.
You can do use delGridRow from the form editing if you need it. I described the way here and used for formatter:'actions' (see here, here and originally here).
var grid = $("#list"),
myDelOptions = {
// because I use "local" data I don't want to send the changes
// to the server so I use "processing:true" setting and delete
// the row manually in onclickSubmit
onclickSubmit: function(options, rowid) {
var grid_id = $.jgrid.jqID(grid[0].id),
grid_p = grid[0].p,
newPage = grid_p.page;
// reset the value of processing option which could be modified
options.processing = true;
// delete the row
grid.delRowData(rowid);
$.jgrid.hideModal("#delmod"+grid_id,
{gb:"#gbox_"+grid_id,
jqm:options.jqModal,onClose:options.onClose});
if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
grid.trigger("reloadGrid", [{page:newPage}]);
}
return true;
},
processing:true
};
and then use
grid.jqGrid('delGridRow', rowid, myDelOptions);
UPDATED: In case of multiselect: true the myDelOptions can be modified to the following:
var grid = $("#list"),
myDelOptions = {
// because I use "local" data I don't want to send the changes
// to the server so I use "processing:true" setting and delete
// the row manually in onclickSubmit
onclickSubmit: function(options) {
var grid_id = $.jgrid.jqID(grid[0].id),
grid_p = grid[0].p,
newPage = grid_p.page,
rowids = grid_p.multiselect? grid_p.selarrrow: [grid_p.selrow];
// reset the value of processing option which could be modified
options.processing = true;
// delete the row
$.each(rowids,function(){
grid.delRowData(this);
});
$.jgrid.hideModal("#delmod"+grid_id,
{gb:"#gbox_"+grid_id,
jqm:options.jqModal,onClose:options.onClose});
if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
grid.trigger("reloadGrid", [{page:newPage}]);
}
return true;
},
processing:true
};
UPDATED 2: To have keyboard support on the Delete operation and to set "Delete" button as default you can add in the delSettings additional option
afterShowForm: function($form) {
var form = $form.parent()[0];
// Delete button: "#dData", Cancel button: "#eData"
$("#dData",form).attr("tabindex","1000");
$("#eData",form).attr("tabindex","1001");
setTimeout(function() {
$("#dData",form).focus(); // set the focus on "Delete" button
},50);
}

Using jQGrid and jQUery tabs how to oprimize the number of grids

I have 3 different tabs where i am displaying data using jQGrids(each tab contain one grid).
But i just thought that my grids are completely the same, only the difference is that they using different url to get data.
So I have three similar girds on each tab only with different urls:
First: url: '/Home/GetData?id=1' Second: url: '/Home/GetData?id=2' and Third: url: '/Home/GetData?id=3'
So i was thinking that may be i may declare grid only once and than on each tab click a can pass the url to load data? So on each tab click jQGrid will be populating from the new url.
May be some one may have any ideas about that?
Or may be some one may have better ideas how to reduce "jQGrid copy-paste" in that case?
UPDATE 0:
Nearly get it work i mean it is working but there is one small problem,
When i am switching tabs the header of the grid getting lost...and some jqgrid formatting as well.
here is my code:
$("#tabs").tabs({
show: function (event, ui) {
if (ui.index == 0) {
//$("#Grid1").appendTo("#tab1");
//$("#Grid1Pager").appendTo("#tab1");
//When Appending only pager and grid div, header getting lost so i've append the whole grid html instead
$("#gbox_Grid1").appendTo("#tab1");
changeGrid("#Grid1", 1);
}
else if (ui.index == 1) {
//$("#Grid1").appendTo("#tab2");
//$("#Grid1Pager").appendTo("#tab2");
$("#gbox_Grid1").appendTo("#tab2");
changeGrid("#Grid1", 2);
}
else if (ui.index == 2) {
//$("#Grid1").appendTo("#tab3");
//$("#Grid1Pager").appendTo("#tab3");
$("#gbox_Grid1").appendTo("#tab3");
changeGrid("#Grid1", 3);
}
}
});
function changeGrid(grid, id) {
$(grid).jqGrid('setGridParam', {
url: '/Home/GetData?id=' + id
});
$(grid).trigger('reloadGrid');
}
UPDATE 1
All right, i've changed the code to append the whole grid instead of appending grid div and pager only. So it is working like that.
You can basically make the tabs as regular buttons that will call some function which sets new URL parameter to the grid and reloads it.
The function should be something like this:
function changeGrid(grid, id) {
$(grid).jqGrid('setGridParam', {
url: '/Home/GetData?id=' + id, page: 1
});
$(grid).trigger('reloadGrid');
}
Note that I set the page to 1. Keep in mind that you might need to set the default sorting column or something similar depending on your solution.
UPDATE
If you really want to go with the tabs, the 'show' event handler can be simplified.
Try this:
$("#tabs").tabs({
show: function (event, ui) {
var id = ui.index + 1;
$("#gbox_Grid1").appendTo("#tab" + id);
$("#Grid1").jqGrid('setGridParam', {
url: '/Home/GetData?id=' + id
});
$("#Grid1").trigger('reloadGrid');
}
});

jqGrid trigger "Loading..." overlay

Does anyone know how to trigger the stock jqGrid "Loading..." overlay that gets displayed when the grid is loading? I know that I can use a jquery plugin without much effort but I'd like to be able to keep the look-n-feel of my application consistent with that of what is already used in jqGrid.
The closes thing I've found is this:
jqGrid display default "loading" message when updating a table / on custom update
n8
If you are searching for something like DisplayLoadingMessage() function. It does not exist in jqGrid. You can only set the loadui option of jqGrid to enable (default), disable or block. I personally prefer block. (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options). But I think it is not what you wanted.
The only thing which you can do, if you like the "Loading..." message from jqGrid, is to make the same one. I'll explain here what jqGrid does to display this message: Two hidden divs will be created. If you have a grid with id=list, this divs will look like following:
<div style="display: none" id="lui_list"
class="ui-widget-overlay jqgrid-overlay"></div>
<div style="display: none" id="load_list"
class="loading ui-state-default ui-state-active">Loading...</div>
where the text "Loading..." or "Lädt..." (in German) comes from $.jgrid.defaults.loadtext. The ids of divs will be constructed from the "lui_" or "load_" prefix and grid id ("list"). Before sending ajax request jqGrid makes one or two of this divs visible. It calls jQuery.show() function for the second div (id="load_list") if loadui option is enable. If loadui option is block, however, then both divs (id="lui_list" and id="load_list") will be shown with respect of .show() function. After the end of ajax request .hide() jQuery function will be called for one or two divs. It's all.
You will find the definition of all css classes in ui.jqgrid.css or jquery-ui-1.8.custom.css.
Now you have enough information to reproduce jqGrid "Loading..." message, but if I were you I would think one more time whether you really want to do this or whether the jQuery blockUI plugin is better for your goals.
I use
$('.loading').show();
$('.loading').hide();
It works fine without creating any new divs
Simple, to show it:
$("#myGrid").closest(".ui-jqgrid").find('.loading').show();
Then to hide it again
$("#myGrid").closest(".ui-jqgrid").find('.loading').hide();
I just placed below line in onSelectRow event of JQ grid it worked.
$('.loading').show();
The style to override is [.ui-jqgrid .loading].
You can call $("#load_").show() and .hide() where is the id of your grid.
its is worling with $('div.loading').show();
This is also useful even other components
$('#editDiv').dialog({
modal : true,
width : 'auto',
height : 'auto',
buttons : {
Ok : function() {
//Call Action to read wo and
**$('div.loading').show();**
var status = call(...)
if(status){
$.ajax({
type : "POST",
url : "./test",
data : {
...
},
async : false,
success : function(data) {
retVal = true;
},
error : function(xhr, status) {
retVal = false;
}
});
}
if (retVal == true) {
retVal = true;
$(this).dialog('close');
}
**$('div.loading').hide();**
},
Cancel : function() {
retVal = false;
$(this).dialog('close');
}
}
});
As mentioned by #Oleg the jQuery Block UI have lots of good features during developing an ajax base applications. With it you can block whole UI or a specific element called element Block
For the jqGrid you can put your grid in a div (sampleGrid) and then block the grid as:
$.extend($.jgrid.defaults, {
ajaxGridOptions : {
beforeSend: function(xhr) {
$("#sampleGrid").block();
},
complete: function(xhr) {
$("#sampleGrid").unblock();
},
error: function(jqXHR, textStatus, errorThrown) {
$("#sampleGrid").unblock();
}
}
});
If you want to not block and not make use of the builtin ajax call to get the data
datatype="local"
you can extend the jqgrid functions like so:
$.jgrid.extend({
// Loading function
loading: function (show) {
if (show === undefined) {
show = true;
}
// All elements of the jQuery object
this.each(function () {
if (!this.grid) return;
// Find the main parent container at level 4
// and display the loading element
$(this).parents().eq(3).find(".loading").toggle(show);
});
return show;
}
});
and then simple call
$("#myGrid").loading();
or
$("#myGrid").loading(true);
to show loading on all your grids (of course changing the grid id per grid) or
$("#myGrid").loading(false);
to hide the loading element, targeting specific grid in case you have multiple grids on the same page
In my issues I used
$('.jsgrid-load-panel').hide()
Then
$('.jsgrid-load-panel').show()

jqGrid - inline edit and trapping edit rules

In my situation, I need to allow users to edit various cells in the grid and then save the whole grid to the server later. I have pretty much solved this issue with inline editing and saving to ‘clientArray’. However, I am trying to use the editRules and have run into some issues.
If I make a column editable, and use edit rules to require it to be a number
{ name: 'Value', index: 'Value', width: 50, sortable: true,edittype: 'text',
editable: true, editoptions: { maxlength: 10 },
editrules:{number: true},
formatter:currencyFmatter, unformat:unformatCurrency },
and I control editing and saving in the onSelectRow event:
onSelectRow: function(id){
if(id && id!==lastSel){
jQuery("#Groups").saveRow(lastSel,true,'clientArray');
jQuery("#Groups").editRow(id,true);
}
lastSel=id
},
I then use a button click event to save the grid. Everything works great untill I put a non-numeric value into the Value cell then click on the row below it. It throw as warning box up and stop the save, but it does not stop me from changing rows. So I now have two rows open for editing. Is there a way to trap the editrule error so I can handle it before moving to the next row.
I have tried to use the functions with saveRow (succesfunc, aftersavefunc, errorfunc, afterrestorefunc), of which all say fire after data is saved to server, which does not appear to work for ‘clientArray’.
Basically, I need to find a way to validate the data in inline editing when saved to ‘clientArray’ and information, suggestions, and particularly, examples would be greatly appreciated.
Thanks.
After playing for awhile, I decided edit rules dont work so well with inLine Editing. So, as you suggested, I made my own validation routine. The trick was figuring out how to get the value of the edited row.
The one thing I am trying to figure out now is how to get the focus to go back to the Value column. Back to the documentation!
if(id && id!==lastSel){
//dont save if first click
if (lastSel != -1) {
//get val of Value to check
var chkval = jQuery("#"+lastSel+"_Value").val() ;
// verify it is a number
if (isNaN(chkval)) {//If not a number
//Send Validation message here
//Restore saved row
jQuery("#Grid").restoreRow(lastSel);
//Return to failed save row
jQuery("#Grid ").setSelection(lastSel,false);
//reopen for editing
jQuery("#Grid ").editRow(lastSel,true);
//Note - dont reset lastSel as you want to stay here }
else {
// If number is good, proceed to save and edit next
jQuery("#Grid ").jqGrid('saveRow',lastSel, checksave, 'clientArray', {}, null, myerrorfunc);
jQuery("#Grid ").editRow(id,true);
lastSel=id;
};
isDirty = true;
};
else {
//first click - open row for editing
alert("new Edit")
jQuery("#Grid ").editRow(id,true);
lastSel=id;}
}
in order to resolve this, I used the plugin jquery.limitkeypress.min.js.
onSelectRow: function(id){
if(id && id!==lastsel){
jQuery('#treegrid').jqGrid('restoreRow',lastsel);
jQuery('#treegrid').jqGrid('editRow',id, true);
$("input[name=Presupuesto]").limitkeypress({ rexp: /^[+]?\d*\.?\d*$/ });
lastsel=id;
}
}
where, "Presupuesto" is the name of the column where I let input data to the user.
It works very good...
To take care of this you can code up your own validation function, myRowIsValid in the example below. Then, just call this function as part of your onSelectRow event handler:
onSelectRow: function(id){
if(id && id!==lastSel){
if (lastSel != null && !myRowIsValid(lastSel) ) {
// Display validation error somehow
return;
}
jQuery("#Groups").saveRow(lastSel,true,'clientArray');
jQuery("#Groups").editRow(id,true);
}
lastSel=id
},
Basically, if the validation fails, then let the user know and do not edit the next row.
I made an array called edit_list, and in the callback oneditfunc I add the rowid to the list, and on aftersavefunc I remove it from the list.
That way you can examine the edit_list in the callbacks to determine if there is a row being edited.
This solution probably did not exist when the OP first asked, but this is how I solved it using the latest jqGrid (4.4.4).
I take advantage of the fact that the saveRow will return true/false on success.
Hopefully this helps.
function StartEditing($grd, id) {
var editparameters = {
"keys": true,
"url": 'clientArray'
};
$grd.jqGrid('editRow', id, editparameters);
$grd[0].LastSel = id;
}
onSelectRow: function(id) {
var $grd = $(this);
if (id && !isNaN($grd[0].LastSel) && id !== $grd[0].LastSel) {
if ($grd.jqGrid('saveRow', $grd[0].LastSel, { "url": 'clientArray' }))
StartEditing($grd, id);
else
$grd.jqGrid('setSelection', $grd[0].LastSel);
}
else
StartEditing($grd, id);
}
To trap edit rules on saveRow event,you can use the inbuilt return type of 'saveRow' .Please mark as answer if you are looking for this
yourcode:
onSelectRow: function(id){
if(id && id!==lastSel){
jQuery("#Groups").saveRow(lastSel,true,'clientArray');
jQuery("#Groups").editRow(id,true);
}
lastSel=id
}
modify code:
onSelectRow: function(id){
if(id && id!==lastSel){
var bool = jQuery("#Groups").saveRow(lastSel,true,'clientArray');
//bool true -->success,false -->invalid row /req field validations
if(bool)
{
//Returns true on sucessful save of record i.e to grid (when using client array)
//and set current selected row to edit mode
jQuery("#Groups").editRow(id,true);
}
else
{
//Set last selected row in edit mode and add required values
jQuery("#Groups").editRow(lastSel,true);
}
}
lastSel=id
}

Resources