jqGrid - Custom button in nav bar added multiples times - javascript

I've added a custom button on my nav bar:
function myFunc(){
$("#grid").jqGrid({
datatype: 'json',
url: 'arquivo.jsp',
jsonReader: {repeatitems: false, root: 'root'},
pager: '#paginado',
rowNum: 10,
autoencode: true,
rowList: [10,20,30],
emptyrecords: "Não há registros.",
recordtext: "Registros {0} - {1} de {2}",
loadtext: "Carregando...",
pgtext: "Página {0} de {1}",
height: 250,
width: 700,
colNames:['Código','Nome', 'Ativo', 'Data Inclusão','Login','Senha','Confirma Senha','Email','Grupos'],
colModel:[
{name:'codigo', width:80, sorttype:"int", editable: true, editrules: { edithidden: true }},
{name:'nome', width:120, editable: true, editrules:{required:true}},
{name:'ativo', width:80, gridview: true, editable: true, edittype:'select', editoptions:{value:{1:'Sim',2:'Não'}}, editrules:{required:true}},
{name:'dataInclusao', width:120, sorttype:"date", datefmt: 'd/M/Y', editable: true, editrules:{required:true, date:true}, editoptions: { dataInit: function(el) { setTimeout(function() { $(el).datepicker({ dateFormat: 'dd/mm/yy' }).val(); }, 200); }}},
{name:'login', width:80, sortable:true, editable: true, editrules:{required:true}},
{name:'senha', width:80, sortable:true, editable: true, hidden:true, edittype:'password', editrules:{edithidden:true, required:true, custom:true, custom_func:validaSenha}},
{name:'confirmaSenha', width:80, sortable:true, editable: true, hidden:true, edittype:'password', editrules:{edithidden:true, required:true}},
{name:'email', width:150, sortable:true, editable: true, editrules:{required:true, email:true}}
],
multiselect: true,
viewrecords: true,
editurl:"data?edit=true",
caption: "Usuários"}
);
$("#grid").jqGrid('navGrid','#paginado',{},
{edit:true,url:"teste?acao=edit",closeAfterEdit:true,reloadAfterSubmit:true,
beforeShowForm: function(form) {
$('#tr_codigo', form).hide();
},
onClickSubmit: function(params, postdata) {
validaSenha();
}
},
{add:true,url:"teste?acao=teste",closeAfterAdd:true,reloadAfterSubmit:true,
beforeShowForm: function(form) {
$('#tr_codigo', form).hide();
},
onClickSubmit: function(params, postdata) {
validaSenha();
}
},
{del:true,reloadAfterSubmit:true,
onclickSubmit: function(url, postdata){
url.url = 'teste?acao=del';
return {codigo: $('#grid').getCell(postdata, 'codigo')};
}
},
{search:true},
{refresh:true}
).navButtonAdd('#paginado',{
caption:"",
buttonicon:"ui-icon-suitcase",
onClickButton: function(){
var dados = $("#grid").jqGrid('getGridParam','selrow');
},
position:"last"
});
};
but everytime I click on the page that shows my grid, a new button is added as you can see in this image:
I don't know if my .jsp can be bringing on this problem but I definitely can't find where the problem is. Hope you guys can help me
Thanks in advance,
Lucas.

I solved the problem using $('#grid').jqGrid('GridUnload');

There is another thread which talks about same issue. In the newer version the syntax got changed. Might help someone. Please refer here
$.jgrid.gridUnload("#jqGridId");

Related

jqgrid - beforeSearch and afterSearch function are not triggered

I am trying to display a progress bar when user tries to filter data in jqgrid. But, the beforeSearch and afterSearch functions are not triggered.
I tried to follow the documentation: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:toolbar_searching but, not sure what I am missing...
Here is the fiddler: http://jsfiddle.net/14f3Lpnk/1/
<table id="list"></table>
<div id="pager"></div>
var mydata = [
{id:"1",invdate:"2010-05-24",name:"test",note:"note",tax:"10.00",total:"2111.00"} ,
{id:"2",invdate:"2010-05-25",name:"test2",note:"note2",tax:"20.00",total:"320.00"},
{id:"3",invdate:"2007-09-01",name:"test3",note:"note3",tax:"30.00",total:"430.00"},
{id:"4",invdate:"2007-10-04",name:"blah",note:"stuff",tax:"10.00",total:"210.00"}
];
jQuery("#list").jqGrid({
data: mydata,
datatype: "local",
height: 150,
rowNum: 10,
ignoreCase: true,
rowList: [10,20,30],
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int"},
{name:'invdate',index:'invdate', width:90, sorttype:"date", formatter:"date"},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right",sorttype:"float", formatter:"number"},
{name:'tax',index:'tax', width:80, align:"right",sorttype:"float"},
{name:'total',index:'total', width:80,align:"right",sorttype:"float"},
{name:'note',index:'note', width:150, sortable:false}
],
pager: "#pager",
viewrecords: true,
autowidth: true,
height: 'auto',
caption: "Test Grid",
beforeSearch: function () {
alert('Filter Started');
},
afterSearch: function () {
alert('Filter Complete');
}
}).jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "cn" });
Any help is appreciated.
beforeSearch and afterSearch are callback functions of filterToolbar method and not the grid itself. So you should use there in the following way
.jqGrid('filterToolbar', {
stringResult: true,
searchOnEnter: true,
defaultSearch: "cn",
beforeSearch: function () {
alert('Filter Started');
},
afterSearch: function () {
alert('Filter Complete');
}
});
See the modified demo http://jsfiddle.net/OlegKi/14f3Lpnk/2/

jQGrid - "jpg1" instead of proper id number

I'm loading local file (I'm parsing csv file into json and then transfer the array to jqGrid). Table generated through jqGrid should allow user to modify, add and delete the data in the grid. Everything seemed to work perfectly until I wanted to add a row to my grid. One of the columns had a parameter key = true which is my id for the rows. When I try to add new row, the grid changes my id into jpg1. The others columns are fine. Below is the code I'm using:
$("#jqGrid").jqGrid({
datatype: "local",
data: myData,
editurl: "clientArray",
colModel: [
{
label: 'Kod',
name: 'Kod',
width: 60,
editable: true,
key: true,
sorttype: 'number'
},
{
label: 'Firma',
name: 'Firma',
width: 120,
editoptions:
{
size: 40,
sopt:['cn']
},
editable: true,
sorttype: 'string'
},
{
label: 'Adres',
name: 'Adres',
width: 80,
editoptions: {size: 40},
editable: true
},
{
label: 'Miasto',
name: 'Miasto',
width: 80,
editoptions:
{
size: 40,
sopt:['cn']
},
editable: true
}
],
height: 'auto',
autowidth: true,
shrinkToFit: false,
forceFit: false,
autoencode: true,
viewrecords: true,
caption: "Title",
pager: "#jqGridPager",
sortable: true,
ignoreCase: true,
sortname: 'Kod',
sortorder: 'asc',
rowNum: 5,
rowList: [5, 10, 20, "10000:All"],
ondblClickRow: function(rowid) {
$("#jqGrid").jqGrid('editGridRow', rowid,
{
editCaption: "The Edit Dialog",
zIndex:100,
recreateForm: true,
closeAfterEdit: true,
width: 900,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
}
});
$('#jqGrid').jqGrid('navGrid',"#jqGridPager",
{ edit: true, add: true, del: true, search: false, refresh: true, view: true, cloneToTop: true},
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
zIndex:100,
recreateForm: true,
closeAfterEdit: true,
reloadAfterSubmit: true,
width: 900,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
width: 900,
zIndex:100,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dialog
delSettings,
// options for the Search Dialog
{
zIndex:100
},
// options for the View Dialog
{
width: '100%'
});
I'm attaching a screenshot that shows a problem:
Photo
The data I use is a file parsed into JSON array via Papaparse.js plugin.
EDIT:
I've added the test data if somebody would like to test the code.
var myData = [];
myData.push(
{
Kod: 1.1,
Firma: 'Hutchinson',
Adres: '5th Avenue',
Miasto: 'Wroclaw'
},
{
Kod: 2.1,
Firma: 'BMW',
Adres: '6th Avenue',
Miasto: 'Warsaw'
});
I will be grateful for any help.
If you need the grid only for local editing, you can consider just remove key: true property to solve the problem. It's the way, which I would recommend you. You can include id property in the input data which will be used as value of rowid (id of <tr> elements).
Alternatively you can change the block "options for the Add Dialog" to the following
// options for the Add Dialog
{
width: 900,
zIndex:100,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: true,
onclickSubmit: function (options, postdata, frmoper) {
// save Kod in some other parameter
return {myKod: postdata.Kod};
},
afterSubmit: function (jqXHR,postdata, frmoper) {
// restore the correct value
postdata.Kod = postdata.myKod;
// inform jqGrid that it was not an error
return [true];
}
},
You still don't would be able to change the id of the row in the way.
By the way you wrote that you use jqGrid 4.7.1. I want remind you that jqGrid 4.7.0 is the last version which is free. It's the reason why I started free jqGrid project which still free. You can get it here (see readme and wiki).
The demo shows an example of the above code fixes using free jqGrid 4.8.

Server paging in kendo grid in web forms

I am trying to load a kendo grid data from an aspx page. I am unable to perform serverpaging. I tried setting serverpaging : true. But still it is taking a lot of time to load grid.
Data from aspx page is retrieved via: Response.Write(JSON_result);
Grid in aspx page is declared as:
var grid = $("#gridAllRuns").kendoGrid({
dataSource: {
transport: {
read: {
url: url_load,
dataType: "json"
},
},
pageSize: 100,
serverPaging: true,
serverSorting: true,
serverFiltering: true
},
height: $(document).height() - 250,
groupable: true,
sortable: true,
reorderable: true,
//selectable: "multiple",
resizable: true,
// serverPaging: true,
// dataBound: resizeGrid,
pageable: {
refresh: true,
pageSizes: [100, 500, 1000],
pageSize: 1000,
buttonCount: 10
},
// toolbar: kendo.template($("#template").html()),
filterable: {
extra: false,
operators: {
string: {
eq: "equal to",
startswith: "starts with",
neq: "not equal to"
}
}
},
toolbar: kendo.template($("#template").html()),
columns: [
{
title: "Name",
field: "FName",
width: 100,
filterable: true
},
{.......}] });
Any help appreciated!

Is it possible to set width of a jQGrid in percentage?

Is it possible to set width of a jQGrid in percentage? If yes, then how?
Not directly but it is possible...
If you are wanting to set the width of the entire grid to a percentage you can use the autowidth property and it will set the grids width to the width of it's parent element (i.e. DIV) and that parent element can have it's percentage set.
autowidth: true
If you want to set the column widths by percentage you can use shrinktofit and then your column width values are basically a percentage.
shrinkToFit: true
These options and many others can be found on the JQGrid wiki
It's possible in very simple way:
$(document).ready(function(){
var pageWidth = $("#updatesList").parent().width() - 100;
$("#updatesList").jqGrid({
url:'quick_updates.php?action=loadUpdates'+"&request=ajax",
datatype: "json",
colNames:[table_heading_id, table_heading_products, table_heading_categories, table_heading_model, table_heading_availability, table_heading_weight, table_heading_quantity, table_heading_sortorder, table_heading_manufacturers, table_heading_price, table_heading_tax],
colModel:[
{name:'id',index:'id', width:(pageWidth*(5/100)), sortable:true, align:"center", search:true},
{name:'name',index:'name', width:(pageWidth*(20/100)), sortable:true, align:"left",true:false,resizable:true},
{name:'categories',index:'categories', width:(pageWidth*(10/100)), sortable:true, align:"left",resizable:true,search:true,stype:"select",searchoptions:{value:categories}},
{name:'model',index:'model', width:(pageWidth*(10/100)), sortable:false, align:"left",search:true,resizable:true,editable:true},
{name:'availability',index:'availability', width:(pageWidth*(10/100)), sortable:true, align:"left",resizable:true,search:true,stype:"select",searchoptions:{value:availability},editable:true,edittype:"select",editoptions:{value:availability}},
{name:'weight',index:'weight', width:(pageWidth*(5/100)), sortable:true, align:"center",search:false,editable:true},
{name:'quantity',index:'quantity', width:(pageWidth*(5/100)), sortable:true, align:"center",search:false,editable:true},
{name:'sortorder',index:'sortorder', width:(pageWidth*(5/100)), sortable:true, align:"center",search:false,editable:true},
{name:'manufacturers',index:'manufacturers', width:(pageWidth*(10/100)), sortable:true, align:"left",resizable:true,search:true,stype:"select",searchoptions:{value:manufacturers},editable:true,edittype:"select",editoptions:{value:manufacturers}},
{name:'price',index:'price', width:(pageWidth*(10/100)), sortable:false, align:"center",search:false},
{name:'tax',index:'tax', width:(pageWidth*(10/100)), sortable:true, align:"center",resizable:true,search:true,stype:"select",searchoptions:{value:taxes},editable:true,edittype:"select",editoptions:{value:taxes}}
],
rowNum:50,
rowList:[10,20,30,50,100],
look at this code:
var pageWidth = $("#updatesList").parent().width() - 100;
and this code:
{name:'id',index:'id', width:(pageWidth*(5/100)), sortable:true, align:"center", search:true},
{name:'name',index:'name', width:(pageWidth*(20/100)),
Datatables 3.5+ supports this via
jQuery("#dt").jqGrid({
autowidth: true,
shrinkToFit: true
});
As for me, I consider this to be the best deсision:
// add this after JqGrid creation
$("#YourTableGrid").setGridWidth( Math.round($(window).width(), true) );
check window size in jquery.
$(window).on("resize", function () {
var newWidth = $("#list").closest(".ui-jqgrid").parent().width();
$("#list").jqGrid("setGridWidth", newWidth, true);
});
make sure to set autowidth: true in grid properties
If you're trying to set the width of the jqgrid table on your HTML page, try this.
HTML
<table id="jqGrid" width="98%"></table>
JS
var outerwidth = $("#jqGrid").width();
$("#jqGrid").jqGrid({
width: outerwidth
});
var operationfieldwidth = 40
function getPercentage(ask)
{
return ((screen.width - operationfieldwidth) * ask) / 100;
}
$(document).ready(function ($) {
GridBind();
});
function GridBind() {
$("#jqGrid").jqGrid({
url: '#(Url.Action("BindRole", "Role"))',
datatype: 'json',
mtype: 'Get',
colNames: ["Role Name", "Role Description", ""],
colModel: [{ name: 'ActRoleName', index: 'RoleName', width: getPercentage(20), align: 'left', power: 3, sortable: true },
{ name: 'ADRoleName', index: 'RoleDesc', width: getPercentage(80), align: 'left', power: 6, sortable: true },
{ name: 'add', sortable: false, width: operationfieldwidth, search: false, power: 0, formatter: addLink }
],
pager: jQuery('#jqControls'),
iconSet: "fontAwesome",
rowNum: 25,
rowList: [25, 50, 100, 500, 1000],
height: screen.height - 490,
viewrecords: true,
emptyrecords: 'No Records are Available to Display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
multiselect: false,
}).navGrid('#jqControls', {
edit: false, add: false, del: false, search: true,
searchtext: "Search", refresh: true
}, {}, {}, {},
{
zIndex: 100,
caption: "Search Record",
sopt: ['cn'],
closeAfterSearch: true
});
}
function addLink(cellvalue, options, rowObject) {
var Str = "<a class='fa fa-pencil-square-o fa-2x' style='cursor:pointer;' href='../../Role/AddEditRole?id=" + rowObject.ID + "'></a>"
return Str;
}
$(document).ready(function () {
var yourPercentage = 50%;
$("#jQGridDemo").setGridWidth($("#jQGridDemo").parent().width() * yourPercentage/100);
});
Percentage calculated in the reference of parent wrapper of jqGrid.

How to hide and show custom buttons in jqGrid by using "reccount"

I'm trying to implement a custom button on a jqGrid with hide and show functionalities. I basically want to show the button if the grid is empty otherwise show.
I have implemented it with the "reccount" method from jqGrid to test if the grid is empty. However i'm not sure if i'm doing it right.
to the end of the code is where i declared the reccount. see "var count".
Thanks in advance.
$("#sessioninfoGrid"+row_id).jqGrid({
url:'/starburst/sessioninfoes/jsonlistbylectureoutline/'+row_id,
datatype: "json",
colNames: ['Session No.','Date','Start Time','End Time','Duration/Hours','Session Type','Topic','Room'],
colModel: [
{name:'sessionNumber',index:'SessionNumber', width:40, formoptions:{elmprefix:'(*) '}, editrules:{required:true}, editable:true, edittype: 'text'},
{name:'sessionDate',index:'sessionDate', width:100, formoptions:{elmprefix:'(*) '}, editrules:{required:true}, editable:true, edittype: 'text',
editoptions: {
dataInit: function(element) {
$(element).datepicker({dateFormat: 'DD, MM dd, yy'})
}
}
},
{name:'starttime',index:'starttime', width:50, formoptions:{elmprefix:'(*) '}, editrules:{required:true}, editable:true, edittype: 'text'
},
{name:'endtime',index:'endtime', width:50, formoptions:{elmprefix:'(*) '}, editrules:{required:true}, editable:true, edittype: 'text'
},
{name:'durationPerSession',index:'durationPerSession', width:50, formoptions:{elmprefix:'(*) '}, editrules:{required:true}, editable:true, edittype: 'text'
},
{name:'sessionType',index:'sessionType', width:50, formoptions:{elmprefix:'(*) '}, editable:true, editrules:{required:true}, edittype: 'select',
editoptions:{value:{}}
},
{name:'topic',index:'topic', width:200, formoptions:{elmprefix:'(*) '}, editable:true, editrules:{required:true}, edittype: 'text',
editoptions: {
dataInit: function(element) {
$(element).width(300)
}
}
},
{name:'room',index:'room', width:35}
],
rowNum:10,
autowidth: true,
pager: sessioninfoPager_id,
sortname: 'id',
viewrecords: true,
sortorder: "desc",
editurl: '<c:url value="/sessioninfoes/update"/>',
caption:"Session Info",
emptyrecords: "Empty Records"
});
$("#sessioninfoGrid"+row_id).jqGrid('navGrid',"#"+sessioninfoPager_id,{edit:false,add:false,del:false,search:true},{ },{ },{ },
{
sopt:['eq', 'ne', 'lt', 'gt', 'cn', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}
);
$("#sessioninfoGrid"+row_id).navButtonAdd("#"+sessioninfoPager_id,
{
caption:"Add",
buttonicon:"ui-icon-plus",
onClickButton: addSessionInfoRow,
position: "last",
title:"Add New Session Info",
cursor: "pointer"
}
);
$("#sessioninfoGrid"+row_id).navButtonAdd("#"+sessioninfoPager_id,
{
caption:"Edit",
buttonicon:"ui-icon-pencil",
onClickButton: editSessionInfoRow,
position: "last",
title:"Edit Session Info",
cursor: "pointer"
}
);
var count= $("#sessioninfoGrid"+row_id).jqGrid('getGridParam','reccount');
if (count == 0){
$("#sessioninfoGrid"+row_id).navButtonAdd("#"+sessioninfoPager_id,
{
caption:"Load Sessions",
buttonicon:"ui-icon-plusthick",
onClickButton: function(){
$.post('<c:url value="/sessioninfoes/autocreate/"/>'+row_id,function(data){
$("#sessioninfoGrid"+row_id).trigger("reloadGrid");
});
},
position: "last",
title:"Load Session Infos",
cursor: "pointer"
}
);
}
The problem with your code is that the grid is loaded asynchronously, which means your call to reccount can happen before the grid is populated, so it returns 0 even though the grid is filled with data a moment later.
One solution is to dynamically hide your button based on whether any data was populated by a server request. For example:
$("#sessioninfoGrid"+row_id).jqGrid({
...
loadComplete: function() {
var count = jQuery("#sessioninfoGrid"+row_id)
.jqGrid('getGridParam','reccount');
if (count === 0){
jQuery('button[title="Load Session Infos"]').hide();
} else {
jQuery('button[title="Load Session Infos"]').show();
}
},
...

Categories

Resources