jquery grid buttons not showing - javascript

The buttons on my jqGrid won't show (back, forward, first page, last page, search, etc...).
Image:
Code:
<h3><?php echo $title?></h3>
<?php $lastbids = SchedulesData::GetLatestBids(); print_r($lastbids);?>
<link rel="stylesheet" type="text/css" media="screen" href="website/lib/js/jqgrid/css/ui.jqgrid.css" />
<script src="website/lib/js/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="website/lib/js/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<table id="grid"></table>
<div id="pager"></div>
<br />
<script type="text/javascript">
$("#grid").jqGrid({
url: 'website/schedules/schedulegrid',
datatype: 'json',
mtype: 'GET',
colNames: ['Code', 'Flight Num', 'Departure', 'Arrival', 'Aircraft', 'Distance', 'Route',
'Bid'],
colModel : [
{index: 'code', name : 'code', width: 40, sortable : true, align: 'center', search: 'true', searchoptions:{sopt:['eq','ne']}},
{index: 'flightnum', name : 'flightnum', width: 65, sortable : true, align: 'center', searchoptions:{sopt:['eq','ne']}},
{index: 'depicao', name : 'depicao', width: 60, sortable : true, align: 'center',searchoptions:{sopt:['eq','ne']}},
{index: 'arricao', name : 'arricao', width: 60, sortable : true, align: 'center',searchoptions:{sopt:['eq','ne']}},
{index: 'a.name', name : 'aircraft', width: 100, sortable : true, align: 'center',searchoptions:{sopt:['in']}},
{index: 'distance', name : 'distance', width: 100, sortable : true, align: 'center', searchoptions:{sopt:['lt','le','gt','ge']}},
{index: 'route', name : 'route', width: 100, sortable : true, align: 'center',searchoptions:{sopt:['in']}},
{index: '', name : '', width: 100, sortable : true, align: 'center', search: false}
],
pager: '#pager', rowNum: 25,
sortname: 'flightnum', sortorder: 'asc',
viewrecords: true, autowidth: true,
height: '100%'
});
jQuery("#grid").jqGrid('navGrid','#pager',
{edit:false,add:false,del:false,search:true,refresh:true},
{}, // edit
{}, // add
{}, //del
{multipleSearch:true} // search options
);
function showroute(schedule_id)
{
$('#jqmdialog').jqm({
ajax:'website/schedules/viewmap?type=schedule&id='+schedule_id
}).jqmShow();
}
function addbid(id)
{
$.post("http://website/schedules/addbid", { id: id },
function()
{
$("#grid").trigger("reloadGrid");
}
);
}
function removebid(id)
{
$.post("http://website/schedules/removebid", { id: id },
function()
{
$("#grid").trigger("reloadGrid");
}
);
}
</script>
I looked at some other posts on stack overflow, but none of them seemed to work for me. How can I get the buttons to show up?

You have to include some jQuery UI CSS file. For example:
<link rel="stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/redmond/jquery-ui.css" />
See example in the documentation.

Related

Add/edit/delete a row in free jqGrid

I am using free jqGrid 4.12.1. I want to add, edit and delete rows in the grid and wish to make server side calls for each operation.
I have added editurl and 'actions' formatter as below,
{
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
}
I am adding 'inlineNav' as below,
$("#itemList").jqGrid('inlineNav',"#itemListPager",
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
},
{
closeOnEscape: true, //Closes the popup on pressing escape key
reloadAfterSubmit: true,
drag: true,
url: "${pageContext.request.contextPath}/billing/saveItem",
errorfunc: function (rowId, resp) {
alert(resp);
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
return [true, '']
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
return [false, response.responseText]//Captures and displays the response text on th Edit window
}
},
editData: {
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{
closeAfterAdd: true, //Closes the add window after add
url: "${pageContext.request.contextPath}/billing/saveItem",
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [true, '']
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [false, response.responseText]
}
}
},
{ //DELETE
closeOnEscape: true,
closeAfterDelete: true,
reloadAfterSubmit: true,
url: "${pageContext.request.contextPath}/billing/saveItem",
drag: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#itemList").trigger("reloadGrid", [{ current: true}]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
return [true, response.responseText]
}
},
delData: {
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{//SEARCH
closeOnEscape: true
}
);
The 'inlineNav' added above has no effect because no server side call is made on adding a new row or deleting existing row. The server side call is made only in case of edit, and that call too does not happen through 'inlineNav' code above. Because even if i remove 'inlineNav' code the server side call is still made to the 'editurl'.
So how can i make server side calls on adding/editing/deleting rows and also pass parameters to these calls. I will really appreciate if someone can point me to a working example somewhere. Thanks
UPDATE:-
I have removed 'actions' formatter and modified code to look as below,
<script type="text/javascript">
var dataGrid = $('#itemList');
var firstClick = true;
$(document).ready(function () {
$('#action').click(function () {
if (!firstClick) {
$("#itemList").setGridParam({datatype:'json'}).trigger("reloadGrid");
}
firstClick = false;
$("#itemList").jqGrid({
url: "${pageContext.request.contextPath}/billing/medicines",
datatype: "json",
//styleUI : 'Bootstrap',
mtype: "POST",
autowidth: true,
shrinkToFit: true,
sortname: "Id",
sortorder: "asc",
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
},
postData: {
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
colNames: ["Id", "Item Type", "Item Code", "Unit", "Stock", "Batch No.", "Expiry Date", "Quantity Per Unit", "Price"],
colModel: [
{ name: "itemId", width: 35, align: "left", sorttype:"int", search: false},
{ name: "itemType", width: 100, align: "left", editable: true},
{ name: "itemCode", width: 120, align: "left", editable: true},
{ name: "unit", width: 70, align: "left", search: false, editable: true},
{ name: "availableQuantity", width: 55, align: "left", search: false, formatter: "number", editable: true},
{ name: "batchNumber", width: 80, align: "left", search: false, editable: true},
{ name: "expiryDate", width: 80, align: "left", search: false, sorttype: "date", editable: true, formatoptions: {srcformat:'d/m/Y', newformat:'d/m/Y'}},
{ name: "quantityPerUnit", width: 80, align: "left", search: false, formatter: "number", editable: true},
{ name: "price", width: 55, align: "left", search: false, formatter: "number", editable: true}
],
pager: "#itemListPager",
rowNum: 50,
rowList: [50, 100, 150, 200],
rownumbers: true,
rownumWidth: 25,
sortname: "id",
sortorder: "desc",
viewrecords: true,
height: '100%',
loadonce: true,
//gridview: true,
autoencode: true,
editurl: "${pageContext.request.contextPath}/billing/saveItem",
caption: "Item List",
ondblClickRow: function(rowId){}
}).navGrid('#itemListPager',{add:false,edit:false,del:true});
$("#itemList").jqGrid('filterToolbar', {autoSearch: true, stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});
$("#itemList").jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
var saveparameters = {
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/saveItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var editparameters = {
"keys" : false,
"oneditfunc" : null,
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/editItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var parameters = {
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon:"ui-icon-plus",
save: true,
saveicon:"ui-icon-disk",
cancel: true,
cancelicon:"ui-icon-cancel",
addParams : saveparameters,
editParams : editparameters
};
$("#itemList").jqGrid('inlineNav',"#itemListPager", parameters);
});
});
</script>
The sample json dada is as,
[
{"itemDetailId":1,"itemId":1,"itemType":"Medicine","itemCode":"Aler-Dryl","itemDesc":"Aler-Dryl","batchNumber":"batch1","expiryDate":"18/02/2017","unit":"tablet","subUnit":"tablet","availableQuantity":120.0,"quantityPerUnit":60.0,"price":122.0},
{"itemDetailId":2,"itemId":2,"itemType":"Medicine","itemCode":"Benadryl","itemDesc":"Benadryl","batchNumber":"batch1","expiryDate":"18/02/2017","unit":"ml","subUnit":"ml","availableQuantity":60.0,"quantityPerUnit":120.0,"price":90.0}
]
Now the url specified in editparameters and saveparameters is getting invoked on editing and adding a row respectively.
Please suggest if above approach is a good one. Also how can we set a request header before edit or save data is posted to server. And i can not find anything like deleteparameters similar to editparameters and saveparameters so that i can use delete specific parameters.
UPDATE 2:-
I could successfully set a request header before server side code is invoked on add/edit row using following code,
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
}});
UPDATE 3:-
Cleaned up code as per Oleg's suggestions as below. But in the strict mode i am getting JS error now - "Uncaught ReferenceError: saveparameters is not defined"
<script type="text/javascript">
$(document).ready(function () {
"use strict";
var dataGrid = $('#itemList');
var firstClick = true;
$('#action').click(function () {
if (!firstClick) {
$("#itemList").setGridParam({datatype:'json'}).trigger("reloadGrid");
}
firstClick = false;
$("#itemList").jqGrid({
url: "${pageContext.request.contextPath}/billing/medicines",
datatype: "json",
mtype: "POST",
autowidth: true,
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
},
colNames: ["Id", "Item Type", "Item Code", "Unit", "Stock", "Batch No.", "Expiry Date", "Quantity Per Unit", "Price"],
colModel: [
{ name: "itemId", width: 35, align: "left", sorttype:"int", search: false, editable: false, key: true},
{ name: "itemType", width: 100, align: "left"},
{ name: "itemCode", width: 120, align: "left"},
{ name: "unit", width: 70, align: "left", search: false},
{ name: "availableQuantity", width: 55, align: "left", search: false, formatter: "number",},
{ name: "batchNumber", width: 80, align: "left", search: false},
{ name: "expiryDate", width: 80, align: "left", search: false, sorttype: "date", formatoptions: {srcformat:'d/m/Y', newformat:'d/m/Y'}},
{ name: "quantityPerUnit", width: 80, align: "left", search: false, formatter: "number"},
{ name: "price", width: 55, align: "left", search: false, formatter: "number"}
],
cmTemplate: {editable: true},
pager: true,
rowNum: 50,
rowList: [50, 100, 150, 200],
rownumbers: true,
rownumWidth: 25,
sortname: "itemType",
sortorder: "asc",
forceClientSorting: true,
viewrecords: true,
height: '100%',
loadonce: true,
//gridview: true,
autoencode: true,
editurl: "${pageContext.request.contextPath}/billing/saveItem",
caption: "Item List"
//ajaxRowOptions: { beforeSend: myTokenSetting }, loadBeforeSend: myTokenSetting where var myTokenSetting = function(jqXHR) { jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val()); }
}).navGrid({add:false,edit:false,del:true});
$("#itemList").jqGrid('filterToolbar', {autoSearch: true, stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});
$("#itemList").jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
var saveparameters = {
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/saveItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var editparameters = {
"keys" : false,
"oneditfunc" : null,
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/editItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var parameters = {
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon:"ui-icon-plus",
save: true,
saveicon:"ui-icon-disk",
cancel: true,
cancelicon:"ui-icon-cancel",
addParams : saveparameters,
editParams : editparameters
};
$("#itemList").jqGrid('inlineNav',parameters);
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
alert('Before Row Send');
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
}});
});
});
</script>
You should examine the options of inlineNav to find out that you use absolutely wrong options:
jQuery("#grid_id").jqGrid('inlineNav', pagerid, parameters);
where parameters have the form
{
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon: "ui-icon-plus",
save: true,
saveicon: "ui-icon-disk",
cancel: true,
cancelicon: "ui-icon-cancel",
addParams: {useFormatter : false},
editParams: {}
}
You use the options of another method navGrid
jQuery("#grid_id").jqGrid('navGrid', '#gridpager', {parameters},
prmEdit, prmAdd, prmDel, prmSearch, prmView);
which allows to use form editing.
You wrote that you want to use both formater: "actions" andinlineNav. Thus you would have to provide some options of inline editing twice. I would recommend you to read [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/New-style-of-usage-options-of-internal-methods). It describes the problems with the usage of form editing usingformatter: "actions"andnavGridtogether. The usage of inline editing have very close problems. You will have to provideaddParamsandeditParamsproperties ofinlineNavand the corresponding options offormatter: "actions"` (see here). To make the code more readable and simple free jqGrid provides another form of editing options.
You can specify all inline editing options inside of inlineEditing option of jqGrid, additional specific options of inlineNav method (if required) in navOptions or in inlineNavOptions, the options of Delete operation in formDeleting and so on. Moreover reloadGrid have the option fromServer: true to restore the original value of datatype ("json", "jsonp", "xml", ...) which you used. You can use reloadGridOptions: { fromServer: true } option of form editing or formDeleting to force reloading from the server.
Moreover your existing code contains many very suspected parts with _id and EmpId. I would strictly recommend you to include the example of format of input JSON data which you use to fill the grid. If you want to use EmpId as the name of rowid why you use _id instead? The code fragment like
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
shows that the current rowid seems be wrong and _id column contains correct information which you need as rowid under the name EmpId.
You can for example use prmNames: { id: "EmpId"} and to add key: true to the column _id. The property key: true in the column _id will inform jqGrid to use the value from the column _id as the rowid and prmNames: { id: "EmpId"} will rename default id property used in Edit and Delete to EmpId. Thus jqGrid will automatically send EmpId parameter with the value from _id column during Delete and Edit operations to the server.
Probably you can remove unneeded column _id from the grid too (at least if you hold the column hidden), but I need to see input data of jqGrid to say you exact options of jqGrid which you can use.
I'm sure that you can essentially reduce your existing code and make it more readable using free jqGrid options, but you have to review your existing code carefully. I suggest you to start with the usage of correct rowid and elimination of all hidden columns which you use. Free jqGrid provides additionalProperties feature which structure is very close to the structure of colModel, but the corresponding properties of input data will be saved in the local data only and not placed in DOM of the table. I can explain all more clear if you would post your existing colModel, jsonReader and example of JSON response returned from the server (1-2 rows of data with dummy data would be enough).

Apply jqgrid search filter toolbar

I am beginner in jqGrid and I have got 2 problems.
Firstly, I want to implement a search toolbar in my grid as shown in the below image.
I have done analysis and found that by using below line of code would enable the search toolbar. But I tried placing it, with no expect6ed output.
jQuery("#overviewJqGrid").jqGrid('navGrid', '#jqGridPager',
{ edit: false, add: false, del: false, search: true }, {}, {}, {}, { closeAfterSearch: true });
JS Code:
app.controller('DiscoveryOverviewCtrl', function ($scope, $rootScope, $compile, localStorageService) {
var gwdth = $("#divGrid").width();
//TODO: Find a better solution
var WebApiServerUrl = $rootScope.WebApiURL;
$('#DiscoveryReportModel').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var reportId = button.data('id');
var machineName = button.data('machinename');
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('#titleSpan').text('Machine Name / IP Address: ' + machineName)
$("#tblDiscoveryReport").jqGrid('setGridParam', { url: $rootScope.WebApiURL + "/discovery/" + reportId, datatype: "json" }).trigger("reloadGrid");
$("#tblDiscoveryReport").jqGrid({
url: $rootScope.WebApiURL + "/discovery/" + reportId,
datatype: "json",
contentType: 'application/json',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) { return JSON.stringify(postData); },
colNames: ['Attribute Name', 'Message', 'Attribute Value'],
colModel: [
{ name: 'attributeName', width: 130 },
{ name: 'message', width: 80 },
{ name: 'attributeValue', formatter: ReportItemStatusImage, width: 40, align: 'center' }
],
loadonce: true,
width: 550,
height: 200,
rowNum: 20,
rowList: [20, 30, 50],
sortname: 'Attribute Name',
viewrecords: true,
gridview: true,
sortable: true,
mtype: 'GET',
loadBeforeSend: function (xhr) {
var authData = localStorageService.get('authorizationData');
if (authData) {
xhr.setRequestHeader("Authorization", 'Bearer ' + authData.token);
}
return xhr;} });
function ReportItemStatusImage(cellvalue, options, rowObject) {
if (cellvalue == true) {
return "<img src='/assets/img/OK.png' height='16' width='16' />";
}
else {
return "<img src='/assets/img/NOK.png' height='16' width='16' />";
}
}
});
$scope.config = {
url: $rootScope.WebApiURL + '/discovery',
datatype: "json",
contentType: 'application/json',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) { return JSON.stringify(postData); },
width: gwdth,
height: 550,
colNames: ['ID', 'Discovery Title', 'Requested Date', 'Completed Date', 'Owner', 'Discovery Status', 'Discoverd Machines'],
colModel: [
{ name: 'id', key: true, width: 50, sorttype: 'int' },
{ name: 'discoveryTitle', width: 80 },
{ name: 'createdDateTime', width: 80, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
{ name: 'discoveryEndDate', width: 80, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
{ name: 'createdByUser', width: 80 },
{ name: 'discoveryRequestStatus', width: 80 },
{ name: 'discoverdMachinesCount', width: 80, sorttype: 'int' }
],
loadonce: true,
rowNum: 10,
rowList: [20, 30, 50],
sortname: 'id',
sortorder: "asc",
viewrecords: true,
gridview: true,
mtype: 'GET',
subGrid: true,
sortable: true,
pager: true,
viewrecords: true,
gridview: true,
mtype: 'GET',
subGridRowExpanded: function (subgrid_id, row_id) {
// we pass two parameters
// subgrid_id is a id of the div tag created within a table
// the row_id is the id of the row
// If we want to pass additional parameters to the url we can use
// the method getRowData(row_id) - which returns associative array in type name-value
// here we can easy construct the following
var subgrid_table_id;
subgrid_table_id = subgrid_id + "_t";
pager_id = "p_" + subgrid_table_id;
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "'></div>");
$("#" + subgrid_table_id).jqGrid({
url: $rootScope.WebApiURL + '/discovery/' + row_id,
datatype: "json",
colNames: ["Id", 'Machine Name / IP Address', 'Status', 'Report'],
colModel: [
{ name: 'id', key: true, width: 50, sorttype: 'int' },
{ name: 'machineName', width: 200 },
{ name: 'isDiscovered', width: 80, edittype: 'image', formatter: isDiscoveredFormatter, align: "center", search: false },
{ name: 'id', label: 'report', formatter: reportFormatter, width: 75, fixed: true, align: 'center', search: false }
],
height: '100%',
loadonce:true,
rowNum: 10,
rowList: [20, 30, 50],
sortable: true,
sortname: 'num',
sortorder: "asc",
pager: pager_id,
loadBeforeSend: function (xhr) {
var authData = localStorageService.get('authorizationData');
if (authData) {
xhr.setRequestHeader("Authorization", 'Bearer ' + authData.token);
}
return xhr;
}
});
jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, { edit: false, add: false, del: false })
},
subGridOptions: {
// configure the icons from theme rolloer
plusicon: "ui-icon-triangle-1-e",
minusicon: "ui-icon-triangle-1-s",
openicon: "ui-icon-arrowreturn-1-e" },
loadBeforeSend: function (xhr) {
var authData = localStorageService.get('authorizationData');
if (authData) {
xhr.setRequestHeader("Authorization", 'Bearer ' + authData.token);
}
return xhr;
}};
var reportFormatter = function (id, cellp, rowData) {
var stateLink = "<button type=\"button\" class=\"btn btn-link\" data-toggle=\"modal\" data-target=\"#DiscoveryReportModel\" data-id=\"" + id + "\" data-machinename=\"" + rowData.machineName + "\">Report</button>";
return stateLink;
};
var isDiscoveredFormatter = function (cellvalue, options, rowObject) {
if (cellvalue == true)
return '<img src="\\assets\\img\\OK.png" height="16" width="16" />';
else
return '<img src="\\assets\\img\\NOK.png" height="16" width="16" />';
};
//Placed here
});
HTML Code:
<div class="modal fade" id="DiscoveryReportModel" tabindex="-1" role="dialog" aria-labelledby="DiscoveryReportModelLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Discovery Report</h4>
</div>
<div class="modal-body">
<div class="well with-header with-footer">
<div class="header bordered-success">
<span id="titleSpan">Some title</span>
</div>
<div id="divReportGrid">
<table id="tblDiscoveryReport"></table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<div class="row" ng-controller="DiscoveryOverviewCtrl">
<div class="col-xs-12 col-md-12">
<div class="widget">
<div class="widget-header bordered-bottom bordered-themeprimary">
<i class="widget-icon fa fa-tasks themeprimary"></i>
<span class="widget-caption">Discovery Overview</span>
</div>
<div id="divGrid" class="widget-body">
<ng-jq-grid id="overviewJqGrid" config="config" api="api"></ng-jq-grid>
<div id="jqGridPager"></div>
</div>
</div>
</div>
The second Problem is that, the search tool bar on other page do not work for date field columns. It do work for 'contains' and 'does not contain' where as 'equal' and other search operations leads to blank output.
I tried using srcformats described in this & referred through this document.
JS Code
$("#jQGridMonitoredMachines").jqGrid({
url: $rootScope.WebApiURL + '/getallmonitoredmachinerequests',
datatype: "json",
contentType: 'application/json',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
colNames: ['Id', 'Machine Name', 'IP Address', 'Discovered Date', 'Agent Install Status', 'Agent Installation Date', 'Agent Status', 'Agent Version', 'Last HeartBeat Received'],
colModel: [
{ name: 'id', hidden: false, width: 20, key: true, sorttype: 'int', search: true },
{ name: 'machineName', width: 120, search: true },
{ name: 'ipAddress', width: 60, search: true },
//{ name: 'discoveredDate', width: 110, formatter: 'date', formatoptions: { srcformat: 'y-m-d', newformat: 'l, F d, Y' } },
//, searchoptions: { sopt: ['eq','ne'], dataInit : function (elem) { $(elem).datepicker({ changeYear: true, changeMonth: true, showButtonPanel: true})} } },
{ name: 'discoveredDate', width: 110, search: true, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
{ name: 'agentInstallStatus', width: 100, search: true },
{ name: 'agentInstallationDate', width: 110, search:true, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
{ name: 'agentStatusName', width: 60, search: true },
{ name: 'agentVersion', width: 50, search: true },
{ name: 'lastHeartBeatRecieved', width: 110, search:true,formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } }
],
rowattr: function (rd) {
if (rd.agentInstallStatus != 'Completed' && rd.agentInstallStatus != 'Upgrade Completed' && rd.agentInstallStatus != 'Uninstallation Failed') {
return {
"class": "ui-state-disabled ui-jqgrid-disablePointerEvents"
};
}
},
sortname: 'id',
sortorder: 'asc',
loadonce: true,
viewrecords: true,
gridview: true,
width: gwdth,
height: 650,
sortable:true,
rowNum: 30,
rowList: [10, 20, 30],
mtype: 'GET',
multiselect: true,
multipleSearch: true,
pager: "#jqGridPager",
What I have to do more in order to get the appropriate functionality working?
When will be executed the code $("#overviewJqGrid").jqGrid('navGrid', '#jqGridPager', ...);? You should validate that it will be executed after the grid is created using to solve your first problem.
It's strictly recommended to use idPrefix for subgrid data to prevent id duplicates (for example idPrefix: "s_" + row_id + "_").
it's probably more effectively to load subgrid data together with the main data
If $('#DiscoveryReportModel').on('show.bs.modal', ... could be called more as once then you should include call of GridUnload instead of setGridParam. It's important to understand that $("#overviewJqGrid").jqGrid({...}) will convert empty <table id="overviewJqGrid"></table> to relatively complex structure of divs and tables. Thus one have two main options to refresh the data on the next call: either setGridParam to change some options and trigger "reloadGrid" or destroying previously created grid using GridUnload and creating new grid in the same place after that using $("#overviewJqGrid").jqGrid({...}). The usage of setGridParam before $("#overviewJqGrid").jqGrid({...}) will not work together.
The last problem with searching for date using "equal" operation seems to me as absolutely separate problem. You use full datetime as the input data and displays there in "m/d/Y h:i:s A" format. It very uncomfortable for the user to type full date with time. The existence of milliseconds in the input data could makes additional problem. The solution could heavy depend on your exact requirements and on the fork of jqGrid which you use. I develop free jqGrid fork since about one year. I implemented custom sorting operations, which allows you to define exactly how you need to compare the data. You can for example compare the dates using Date only "equal" where you compare only the date part ignoring the time part. The old demo, which I created for the old issue demonstrates the feature. One can type (or choose) "04/15/2015" in the demo and the filtered data will be tree lines with "4/15/2015 9:15:40 PM", "4/15/2015 3:31:49 PM" and "4/15/2015 12:00:00 AM":
Finally I want to include one more reference to the old answer which demonstrates the usage of jqGrid with respect of directive of anguler. Probably the example would be helpful for you too.

Jquery datepicker icon position is incorrect

My calendar image is positioned below the text box of my datepicker. How can I solve this misalignment.
This is a screenshot of my screen: ! 1: http://i.stack.imgur.com/3uifN.jpg
See the jsfiddle here: jsfiddle.net/njiterry/yNw3C/8477
This is my jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Country Visibility</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui.min.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="js/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="js/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var mydata = [
{ Sel: true, Country : "Germany", Capital : "Berlin", Date: "05-09-2014"},
{ Sel: true, Country : "France", Capital : "Paris", Date: "05-09-2014" },
{ Sel: true, Country : "Cameroon", Capital : "Yaounde", Date: "06-09-2014" },
{ Sel: true, Country : "Gabon", Capital : "Libreville", Date: "06-09-2014" },
{ Sel: true, Country : "Holland", Capital : "Amsterdam", Date: "07-09-2014" },
{ Sel: true, Country : "Japan", Capital : "Tokyo", Date: "08-09-2014" },
{ Sel: true, Country : "Italy", Capital : "Rome" , Date: "09-09-2014"},
{ Sel: true, Country : "Spain", Capital : "Madrid" , Date: "09-09-2014"},
{ Sel: true, Country : "England", Capital : "London" , Date: "10-09-2014"},
{ Sel: true, Country : "US", Capital : "Washington D.C." , Date: "12-09-2014"}
];
var grid = jQuery("#pays_grid");
var initDateWithButton = function (elem) {
if (/^\d+%$/.test(elem.style.width)) {
// remove % from the searching toolbar
elem.style.width = '';
}
// to be able to use 'showOn' option of datepicker in advance searching dialog
// or in the editing we have to use setTimeout
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-mm-yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
buttonImageOnly: true,
buttonImage: "images/calendar.gif",
buttonText: "Select date",
onSelect: function (dateText, inst) {
if (inst.id.substr(0, 3) === "gs_") {
grid[0].triggerToolbar();
}
else {
// to refresh the filter
$(inst).trigger("change");
}
}
});
$(".ui-datepicker-trigger").css({
position: "relative",
marginLeft: "1px",
marginTop: "0px",
});
}, 100);
};
grid.jqGrid({ //set your grid id
data: mydata, //insert data from the data object we created above
datatype: 'local',
height: 230,
autoheight: true,
width: 800,
rowNum: 10,
rowList: [1, 5, 10],
colNames:['Sel.','Id','Name', 'Date'], //define column names
colModel:[
{name: 'Sel', align: 'center', sortable: false, width: 25, search: false, editable: true, edittype: 'checkbox',
editoptions: { value: "True:False" }, formatter: "checkbox", formatoptions: { disabled: false} },
{name:'Country', index:'Country', key: true, width:50, align:'center'},
{name:'Capital', index:'Capital', width:100, align:'center'},
{name: 'Date', index: 'Date', align: 'center', width: 100}
], //define column models
pager: '#pager', //set your pager div id
sortname: 'Country', //the column according to which data is to be sorted; optional
viewrecords: true, //if true, displays the total number of records, etc. as: "View X to Y out of Z” optional
sortorder: "asc", //sort order; optional
sortname: 'Country',
shrinkToFit: true,
forceFit: true,
caption: "Country Overview", //title of grid
loadComplete: function() {
grid.jqGrid('setColProp', 'Date', {
sorttype: 'date', editable: true,
editoptions: { dataInit: initDateWithButton, size: 11 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton,
// size: 8, // for the advanced searching dialog
// attr: {size: 8} // for the searching toolbar
}
});
grid.jqGrid('filterToolbar', {autoSearch: true});
}
}).navGrid('#truck_grid_pager', {edit: false, add: false, del: false, search: false, refresh: true});
});
</script>
</head>
<body>
<table id="pays_grid"></table>
<div id="pager"></div>
</body>
</html>
I've tried looking at similar questions here on Stack Overflow but I can't get the trigger image to appear inline with the input.
It seems to me that you should use
.ui-jqgrid .ui-search-table .ui-search-input > input,
.ui-jqgrid .ui-search-table .ui-search-input > select,
.ui-jqgrid .ui-search-table .ui-search-input > img {
vertical-align: middle;
display: inline-block;
}
See http://jsfiddle.net/yNw3C/8486/
add display inline style to your text box that contains date
then adjust the margin-top of your date picker image to make it look nice and aligned with your text box.
check here: http://jsfiddle.net/saxenaabhi6/yNw3C/8479/
#gs_Date{
display:inline
}
Instead of setting
position='relative'
set
position='absolute'
and adjust top and left accordingly. Here's a fiddle:
http://jsfiddle.net/ey170t1z/1/
in the CSS:
.ui-datepicker-trigger {
vertical-align: top;
height: 24px; /* the same of textbox */
}

Javascript variable into postdata of jqGrid

Right now I have this postData: { search: function() { return $("#search").val(); },},
I then have jQuery function above the jqGrid function that performs some logic and produces a string variable. Right now I am just taking that variable and setting the value of the search element like this:
$("#startSearch").click(function() {
$("#search").val(searchVal);
$("#grid").trigger("reloadGrid");
});
This works but I was hopping to do this differently. I want to just pass the seachVal variable that my jQuery function produces right into the postdata.
I tried it like this but its not working postData: { search: function() { return searchVal; },},
I'm getting an error that says searchVal is not defined. I made sure that the searchVal variable is global but it is still not working.
Is this possible or am I just looking at this wrong?
Any help would be great.
Thanks
UPDATE:
Here is a stripped down version of the page:
<fieldset>
<input type='text' id='search' />
<button type='button' id='startSearch'>Search</button>
</fieldset>
<script type="text/javascript">
$(function(){
$("#startSearch").click(function() {
serchVal = 'transID > "5"';
$("#search").val(serchVal);
$("#grid").trigger("reloadGrid");
});
$("#list").jqGrid({
url:'data.cfc?method=gridData',
datatype: 'json',
mtype: 'POST',
jsonReader : {
root: "rows",
page: "currentpage",
total: "totalpages",
records: "totalrecords",
repeatitems: false,
id: "0",
},
postData: { search: function() { return $("#search").val(); },},
colModel :[
{name:'transid', label:'Trans ID', width:60},
{name:'companyname', label:'Company Name', width:245},
{name:'companycode', label:'Company Code', width:245},
{name:'datasource', label:'Datasource', width:245}
],
pager: '#pager',
rowList:[10,50,100],
rowNum:'10',
height:221,
sortname: 'transid',
sortorder: 'asc',
viewrecords: true,
gridview: true,
caption: 'Get Trans',
altRows: false,
autowidth: true,
forceFit: true,
rownumbers: true,
scroll: false,
sortable: true
});
$("#list").jqGrid('navGrid','#pager',{edit:false,add:false,del:false,search:false,view:true});
});
</script>
<table id="grid"></table>
<div id="pager"></div>
I suppose the problem exist just because you didn't declared the variable serchVal (you means probably searchVal). You can try to modify the code to the following
$(function () {
var searchVal = '';
$("#startSearch").click(function () {
searchVal = 'transID > "5"';
$("#grid").trigger("reloadGrid");
});
$("#list").jqGrid({
url: 'data.cfc?method=gridData',
datatype: 'json',
mtype: 'POST',
jsonReader : {
page: "currentpage",
total: "totalpages",
records: "totalrecords",
repeatitems: false,
id: "0"
},
postData: { search: function () { return searchVal; }},
colModel: [
{name: 'transid', label: 'Trans ID', width: 60},
{name: 'companyname', label: 'Company Name', width: 245},
{name: 'companycode', label: 'Company Code', width: 245},
{name: 'datasource', label: 'Datasource', width: 245}
],
pager: '#pager',
rowList: [10, 50, 100],
rowNum: 10,
height: 221,
sortname: 'transid',
viewrecords: true,
gridview: true,
caption: 'Get Trans',
autowidth: true,
rownumbers: true,
sortable: true
}).jqGrid('navGrid', '#pager',
{edit: false, add: false, del: false, search: false, view: true});
});
After that you can remove <input type='text' id='search' />.
Why don't you just wrap your logic in a function
function SomeLogic() {
return("some logic here!");
}
which is going to be called like this:
postData: { search: function() { return SomeLogic() } },
so you just have to reload the grid
$("#startSearch").click(function() {
$("#grid").trigger("reloadGrid");
});
obviously your function SomeLogic can just return searchVal
function SomeLogic() {
return(searchVal);
}

Flexigrid doesn't work with jQuery 1.4.3?

I am trying to use flexigrid plugin for jquery, the problem is that I also want to use the plugin fancybox, and this plugin uses jQuery 1.4.3, but flexigrid doesn't seem to work with that version of jquery.
When I roll back to the old jquery version that comes with flexigrid the grid does work but fancybox doesn't.
This is the code i am using:
$("#grid1").flexigrid
(
{
url: 'php/get.php',
dataType: 'json',
colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'center'},
{display: 'Name', name : 'name', width : 180, sortable : true, align: 'left'},
{display: 'Email', name : 'email', width : 120, sortable : true, align: 'left'},
{display: 'tID', name : 'tid', width : 130, sortable : true, align: 'left'},
{display: 'Active', name : 'numcode', width : 80, sortable : true, align: 'right'}
],
buttons : [
{name: 'Add', bclass: 'add', onpress : doAction},
{separator: true},
{name: 'Delete', bclass: 'delete', onpress : doAction},
{separator: true},
{name: 'Activate', bclass: 'activate', onpress : doAction},
{separator: true},
{name: 'Deactivate', bclass: 'deactivate', onpress : doAction},
{separator: true}
],
searchitems : [
{display: 'Name', name : 'name', isdefault: true}
],
sortname: "id",
sortorder: "asc",
usepager: true,
title: 'XXX',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 700,
height: 200
}
);
</script>
And the php response looks like this:
{
page: 1,
total: 3,
rows: [
{id:'28',cell:['28','test','test','test','1']},
{id:'27',cell:['27','test','test','test','1']},
{id:'26',cell:['26','etrer','ter','trt','0']}]
}
I am using firebug and it doesn't show any js error.
Is there a way to use flexigid with jquery 1.4.3?
Try rendering your JSON using double quotes, not single quotes.
Both plugins seems to work with v1.3.2
I think I have both plugins working with jQuery 1.6.1. Obviously it depends on both flexigrid and fancybox jQuery plugins and an example JSON file that I have called flexigrid.json. If you download those plugins and make sure the src and href links to the correct locations for the JavaScript and CSS and create a file called flexigrid.json with the following content:
{
"page": 1,
"total": 3,
"rows": [
{"id":28,"cell":[28,"test","test","test",1]},
{"id":27,"cell":[27,"test","test","test",1]},
{"id":26,"cell":[26,"etrer","ter","trt",0]}]
}
Note: The JSON in your example is not valid (as #Josh pointed out already). You can run in through an online parser to see the errors.
Here is the example page with both plugins:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script src="flexigrid/js/flexigrid.pack.js" type="text/javascript"></script>
<link type="text/css" rel="stylesheet" href="flexigrid/css/flexigrid.pack.css"/>
<script src="fancybox/jquery.fancybox-1.3.4.js" type="text/javascript"></script>
<link type="text/css" rel="stylesheet" href="fancybox/jquery.fancybox-1.3.4.css"/>
<script type="text/javascript" src="fancybox/jquery.easing-1.3.pack.js"></script>
<script type="text/javascript">
$(function(){
function doAction() {}
$("#grid1").flexigrid({
url: 'flexigrid.json',
dataType: 'json',
colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'center'},
{display: 'Name', name : 'name', width : 180, sortable : true, align: 'left'},
{display: 'Email', name : 'email', width : 120, sortable : true, align: 'left'},
{display: 'tID', name : 'tid', width : 130, sortable : true, align: 'left'},
{display: 'Active', name : 'numcode', width : 80, sortable : true, align: 'right'}
],
buttons : [
{name: 'Add', bclass: 'add', onpress : doAction},
{separator: true},
{name: 'Delete', bclass: 'delete', onpress : doAction},
{separator: true},
{name: 'Activate', bclass: 'activate', onpress : doAction},
{separator: true},
{name: 'Deactivate', bclass: 'deactivate', onpress : doAction},
{separator: true}
],
searchitems : [
{display: 'Name', name : 'name', isdefault: true}
],
sortname: "id",
sortorder: "asc",
usepager: true,
title: 'XXX',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 700,
height: 200
});
$("a#example1").fancybox({
'titleShow' : false
});
$("a#example2").fancybox({
'titleShow' : false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'easingIn' : 'easeOutBack',
'easingOut' : 'easeInBack'
});
$("a#example3").fancybox({
'titleShow' : false,
'transitionIn' : 'none',
'transitionOut' : 'none'
});
});
</script>
</head>
<body>
<table id="grid1"><tr><td></td></tr></table>
<p>Different animations - 'fade', 'elastic' and 'none'<br />
<a id="example1" href="http://farm5.static.flickr.com/4058/4252054277_f0fa91e026.jpg">
<img alt="example1" src="http://farm5.static.flickr.com/4058/4252054277_f0fa91e026_m.jpg" />
</a>
<a id="example2" href="http://farm3.static.flickr.com/2489/4234944202_0fe7930011.jpg">
<img alt="example2" src="http://farm3.static.flickr.com/2489/4234944202_0fe7930011_m.jpg" />
</a>
<a id="example3" href="http://farm3.static.flickr.com/2647/3867677191_04d8d52b1a.jpg">
<img alt="example3" src="http://farm3.static.flickr.com/2647/3867677191_04d8d52b1a_m.jpg" />
</a>
</p>
</body>
</html>
Note: This will not work locally when testing in Chrome 13 due to the Same origin policy security restriction. You can see the error in the console Origin null is not allowed by Access-Control-Allow-Origin. You will need to serve to the example page and JSON from a proper web server.
Hope this helps.
I am working on the same issue. I found the below links helpful to get started.
Core issue - from groups.google.com
"As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double- quotes. For details on the JSON format, see http://json.org/.
Basically you have to be careful with your json now, and ensure its formatted correctly. I would guess its related to this. Check the json.org site and check your JSON to make sure its correct."
http://simonwillison.net/2006/oct/11/json/
http://jsonformatter.curiousconcept.com/#jsonformatter

Categories

Resources