Related
i have a map section in html and javascript, the section is like below:
CustomMarker.prototype = new google.maps.OverlayView();
function CustomMarker(opts) {
this.setValues(opts);
}
CustomMarker.prototype.draw = function() {
var self = this;
var div = this.div;
if (!div) {
div = this.div = $('' +
'<div>' +
'<div class="shadow"></div>' +
'<div class="pulse"></div>' +
'<div class="pin-wrap">' +
'<div class="pin"></div>' +
'</div>' +
'</div>' +
'')[0];
this.pinWrap = this.div.getElementsByClassName('pin-wrap');
this.pin = this.div.getElementsByClassName('pin');
this.pinShadow = this.div.getElementsByClassName('shadow');
div.style.position = 'absolute';
div.style.cursor = 'pointer';
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
google.maps.event.addDomListener(div, "click", function(event) {
google.maps.event.trigger(self, "click", event);
});
}
var point = this.getProjection().fromLatLngToDivPixel(this.position);
if (point) {
div.style.left = point.x + 'px';
div.style.top = point.y + 'px';
}
};
CustomMarker.prototype.animateDrop = function() {
dynamics.stop(this.pinWrap);
dynamics.css(this.pinWrap, {
'transform': 'scaleY(2) translateY(-' + $('#map').outerHeight() + 'px)',
'opacity': '1',
});
dynamics.animate(this.pinWrap, {
translateY: 0,
scaleY: 1.0,
}, {
type: dynamics.gravity,
duration: 1800,
});
dynamics.stop(this.pin);
dynamics.css(this.pin, {
'transform': 'none',
});
dynamics.animate(this.pin, {
scaleY: 0.8
}, {
type: dynamics.bounce,
duration: 1800,
bounciness: 600,
})
dynamics.stop(this.pinShadow);
dynamics.css(this.pinShadow, {
'transform': 'scale(0,0)',
});
dynamics.animate(this.pinShadow, {
scale: 1,
}, {
type: dynamics.gravity,
duration: 1800,
});
}
CustomMarker.prototype.animateBounce = function() {
dynamics.stop(this.pinWrap);
dynamics.css(this.pinWrap, {
'transform': 'none',
});
dynamics.animate(this.pinWrap, {
translateY: -30
}, {
type: dynamics.forceWithGravity,
bounciness: 0,
duration: 500,
delay: 150,
});
dynamics.stop(this.pin);
dynamics.css(this.pin, {
'transform': 'none',
});
dynamics.animate(this.pin, {
scaleY: 0.8
}, {
type: dynamics.bounce,
duration: 800,
bounciness: 0,
});
dynamics.animate(this.pin, {
scaleY: 0.8
}, {
type: dynamics.bounce,
duration: 800,
bounciness: 600,
delay: 650,
});
dynamics.stop(this.pinShadow);
dynamics.css(this.pinShadow, {
'transform': 'none',
});
dynamics.animate(this.pinShadow, {
scale: 0.6,
}, {
type: dynamics.forceWithGravity,
bounciness: 0,
duration: 500,
delay: 150,
});
}
CustomMarker.prototype.animateWobble = function() {
dynamics.stop(this.pinWrap);
dynamics.css(this.pinWrap, {
'transform': 'none',
});
dynamics.animate(this.pinWrap, {
rotateZ: -45,
}, {
type: dynamics.bounce,
duration: 1800,
});
dynamics.stop(this.pin);
dynamics.css(this.pin, {
'transform': 'none',
});
dynamics.animate(this.pin, {
scaleX: 0.8
}, {
type: dynamics.bounce,
duration: 800,
bounciness: 1800,
});
}
$(function() {
var pos = new google.maps.LatLng(17.402507, 78.484450);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: pos,
disableDefaultUI: true,
});
var marker = new CustomMarker({
position: pos,
map: map,
});
google.maps.event.addListener(marker, 'click', function(e) {
marker.animateWobble();
});
$('#drop').on('click', function(e) {
marker.animateDrop();
});
$('#wobble').on('click', function(e) {
marker.animateWobble();
});
$('#bounce').on('click', function(e) {
marker.animateBounce();
})
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="styles.css" type="text/css">
<link href='//fonts.googleapis.com/css?family=Raleway:600,900,400|Roboto:300,700' rel='stylesheet'>
<div id="map">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d15228.829609290426!2d78.46827062015056!3d17.401831576090753!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3bcb9900853b7663%3A0xff5ff705a04cebb!2sBook%20The%20Party!5e0!3m2!1sen!2sin!4v1597715101831!5m2!1sen!2sin"
width="600" height="450" frameborder="0" style="border:0;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe>
</div>
I added my latitude and longitude inside the javascript, but its not properly loading, its still showing maps not loaded correctly. as i am new to this, I searched on google and saw I need to add API key on this, but where do I add API key in this code, please anyone help. thanks in advance
Try to change this line:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
to this:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&key=YOUR_API_KEY" type="text/javascript"></script>
I have jqgrid page with a lot of columns. Idea is to allow user choose columns and their order in table and save this order and column count in cookies. For this purposes I use $.jgrid.saveState() for saving and $.jgrid.loadState() for restoring jqgrid options from cookies. This methods works fine. But I don't want to save data to storage: only column order and filter. I tried option restoreData: false and storeData: false, but it didn't work.
Here the code of my jqgrid:
jQuery(function ($) {
var table = $("#table");
var pager = "#pager";
var search_panel = "#search";
var localization = globalLocale;
var colNames = [ "Mobile direction total time (sec)", "Mobile direction q-ty ", "Mobile time Percent",
"City direction total time (sec)", "City direction q-ty", 'City time Percent' ];
var exportToCsvBut = "Export to excell";
resizeToFitPageSize(table);
resizeOnSidebar(table);
$(function () {
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
var defCurDate = moment().startOf('day').format('DD.MM.YYYY HH:mm:ss');
var defNextDate = moment().endOf('day').format('DD.MM.YYYY HH:mm:ss');
var from = $('#datetimepickerFrom');
var to = $('#datetimepickerTo');
if (from.val() === "" || to.val() === "") {
from.val(defCurDate);
to.val(defNextDate);
}
$("#datetimepickerFrom").datetimepicker({
dateFormat: 'dd.mm.yy',
timeFormat: 'HH:mm:ss',
defaultDate: new Date(year, month, day + 1, 00, 00),
onClose: function () {
beforeRefresh();
}
});
$("#datetimepickerTo").datetimepicker({
dateFormat: 'dd.mm.yy',
timeFormat: 'HH:mm:ss',
defaultDate: new Date(year, month, day + 1, 00, 00),
onClose: function () {
beforeRefresh();
}
});
defCurDate = $('#datetimepickerFrom').val();
defNextDate = $('#datetimepickerTo').val();
});
var initDate = function (elem) {
$(elem).datetimepicker({
dateFormat: 'd.m.Y H:i:s',
showButtonPanel: true
});
};
var template = {width: 160, fixed: true, align: 'center', editable: false, stype: 'text'};
var colModel = [
{
name: 'mobileDirectionTotalTime',
index: 'mobileDirectionTotalTime',
sortname: 'mobileDirectionTotalTime',
template: template,
formatter: nullFormatter,
sorttype: 'number'
},
{
name: 'mobileDirectionQty',
index: 'mobileDirectionQty',
sortname: 'mobileDirectionQty',
template: template,
formatter: nullFormatter,
sorttype: 'number'
},
{
name: 'mobileDirectionPercent',
index: 'mobileDirectionPercent',
sortname: 'mobileDirectionPercent',
width: 120,
fixed: true, align: 'center', editable: false,
template: "number",
sorttype: 'number'
},
{
name: 'cityDirectionTotalTime',
edittype: "custom",
sortname: 'cityDirectionTotalTime',
formatter: null,
sorttype: 'number'
},
{
name: 'cityDirectionQty',
index: 'cityDirectionQty',
sortname: 'cityDirectionQty',
template: template,
sorttype: 'number'
},
{
name: 'cityDirectionTimePercent',
index: 'cityDirectionTimePercent',
sortname: 'cityDirectionTimePercent',
template: template,
sorttype: 'number'
},
];
table.jqGrid({
url: URL_DATA,
datatype: "json",
jsonReader: {
repeatitems: true
},
height: 'auto',
colNames: colNames,
colModel: colModel,
shrinkToFit: false,
forceFit: true,
pager: pager,
toppager: true,
rowNum: 10,
rowList: [5, 10, 15, 20, 25, 30],
loadonce: true,
viewrecords: true,
storeNavOptions : true,
// navOptions: {reloadGridOptions: {fromServer: true}},
loadComplete: function () {
var table = this;
setTimeout(function () {
updatePagerIcons(table);
enableTooltips(table);
}, 0);
},
gridComplete: function () {
/*var idarray = table.jqGrid('getDataIDs');
if (idarray.length > 0) {
var firstid = table.jqGrid('getDataIDs')[0];
table.setSelection(firstid);
}*/
}
});
$(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size
function beforeRefresh() {
var from = $('#datetimepickerFrom');
var to = $('#datetimepickerTo');
if (from.val() != null && from.val() != '' && to.val() != null && to.val() != '') {
resetFilter('table', 'globalSearchText');
table.jqGrid().setGridParam({datatype: 'json'}).setGridParam({url: URL_DATA + "?from=" + from.val() + "&to=" + to.val()}).trigger("reloadGrid")
if (from.val() === "" || to.val() === "") {
from.val(defCurDate);
to.val(defNextDate);
}
}
}
//navButtons
table.jqGrid('navGrid', pager,
{ //navbar options
cloneToTop: true,
edit: false,
add: false,
del: false,
search: true,
searchicon: 'ace-icon fa fa-search orange',
refresh: true,
beforeRefresh: function () {
var from = $('#datetimepickerFrom');
var to = $('#datetimepickerTo');
if (from.val() != null && from.val() != '' && to.val() != null && to.val() != '') {
resetFilter('table', 'globalSearchText');
table.jqGrid().setGridParam({datatype: 'json'}).setGridParam({url: URL_DATA + "?from=" + from.val() + "&to=" + to.val()}).trigger("reloadGrid")
if (from.val() === "" || to.val() === "") {
from.val(defCurDate);
to.val(defNextDate);
}
}
},
refreshicon: 'ace-icon fa fa fa-refresh green',
view: true,
viewicon: 'ace-icon fa fa-search-plus grey'
}, {}, {}, {},
{
multipleSearch: true,
searchOnEnter: true,
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
},
{
//view record form
recreateForm: true,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
form.closest('div.ui-jqdialog').center();
}
}
);
addToolButton({
caption: "",
buttonicon: "ace-icon fa fa-calculator blue",
title: "Выбрать столбцы",
onClickButton: function () {
$(this).jqGrid('columnChooser',
{
width: 550,
msel_opts: {dividerLocation: 0.5}, modal: true
});
$("#colchooser_" + $.jgrid.jqID(this.id) + ' div.available>div.actions')
.prepend('<label style="float:left;position:relative;margin-left:0.6em;top:0.6em">Поиск:</label>');
}
}, table, pager);
addSearchField('table', 'globalSearchText');
$(window).triggerHandler('resize.jqGrid');
table.triggerHandler("jqGridAfterGridComplete");
destroyGrid(table);
$('#table')
.append($("<div style='margin-top: 10px'>" +
"<button id='savestate'>save state</button>" +"<button id='loadstate'>load state</button>" +
"</div>"));
$("#savestate").click(function(){
$.jgrid.saveState("table");
});
$("#loadstate").click(function(){
$.jgrid.loadState("table", {}, {});
})
});
document.addEventListener('contextmenu', function (e) {
e.preventDefault();
});
Here the view of table page:
After user press load state and save state it displays data which was before but not actual:
It just show data which was saved in localstorage.
If I add storeData: false it just diplayed table with no data and doens't load new data from server.
Can anyone help?
P.S In case someone will have the same problem:
$("#table").jqGrid().setGridParam({datatype:'json'}).setGridParam({url : URL_DATA}).trigger("reloadGrid"); after $.jgrid.loadState("table", '', { restoreData: false}); will load new data in loaded grid.
I recommend you to use restoreData: false in loadState and after this command to reload the grid with trigger by example
$("#loadstate").click(function(){
$.jgrid.loadState("table", '', { restoreData: false});
$("#table").trigger("reloadGrid");
});
This will reload fresh grid data from server with the current setting
I have the following function:
var handsonTableHandler = (function () {
var container = document.getElementById('WebGrid');
var hot = "";
var init = function () {
//container is null here, why?
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
hot = new Handsontable(container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
}
}
$(document).ready(function() {
handsonTableHandler.init();
});
I want the container and hot variable to be accessible through the whole function, thus, in the init function and other functions that are defined here.
As you can see, I'm getting the element for with the Id WebGrid. But in the init-function, it's null. Why is this?
If it was not accessable in the inner function, it would be "Undefined" instead of "Null", therefore it is accessable
you did
var container = document.getElementById('WebGrid');
but document.getElementById(...) returns Null if the element does not exist, therefore there mustnt have been an element with the id of WebGrid
Try in the console and type
document.getElementById('WebGrid')
if it returns null, then there was no element in the first place
now change your code to:
$(document).ready(function() {
var handsonTableHandler = (function () {
var container = document.getElementById('WebGrid');
var hot = "";
var init = function () {
//container is null here, why?
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
hot = new Handsontable(container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
};
})();
handsonTableHandler.init();
});
The only to fix this, is to assign the DOM element to container in init, like this:
var handsonTableHandler = (function () {
var container,
hot;
var init = function () {
container = document.getElementById('WebGrid');
//container is null here, why?
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
hot = new Handsontable(container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
}
})()
You can change you function to create handler with new syntax and get access to .init function
let handsonTableHandler = function () {
this.container = document.getElementById('WebGrid');
this.hot = "";
this.init = function () {
console.log('container', this.container);
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
this.hot = new Handsontable(this.container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
}
}
let handler = new handsonTableHandler();
$(document).ready(function() {
handler.init(); // output: container not null
});
to me it seems you are not running the function so the closure is never created, I added a few parenthesis, this should create the closure:
var handsonTableHandler = function () {
var container = document.getElementById('WebGrid');
var hot = "";
var init = function () {
//container is null here, why?
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
hot = new Handsontable(container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
}
return {init: init}
};
$(document).ready(function() {
handsonTableHandler().init();
});
I'm trying to drag a dialog in a web app and its not working why?
My code is something like this... draggable is set to true but still its not dragging... and for your info there is movable objects in the background also. dragging symbol is shown but the dialog is not moving why? Can you explain how to make a dialog draggable?
$dlgLibrary = $('<div style="overflow-y:hidden;color:#FBFBEF"" id="eBLibrary"></div>')
.dialog({
autoOpen: false,
title: 'Browse & Select',
maxWidth:1000,
maxHeight: 600,
width: 800,
height: 600,
dialogClass: "alertDialog",
modal: true,
closeOnEscape: true,
canMaximize:true,
draggable: true,
resizeHt: 0,
resizeWd: 0,
resizeStop: function(event, ui) {
if (resizeHt== 0 && resizeWd== 0) {
resizeHt = $dlgLibrary.dialog( "option", "height" );
resizeWd = $dlgLibrary.dialog( "option", "width" );
};
$('#eBLibrary-Show').width(Number(resizeWd-(resizeWd*16/100)));$('#eBLibrary-Show').height(Number(resizeHt-(resizeHt*35/100)));
resizeHt= 0;
resizeWd= 0;
},
open: function(event, ui) {
}
$.ajax({ url: './Library.html',
success : function(data) {
},
buttons: libButtons,
close: function() {
});
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index3</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$dlgLibrary =
$(function () {
$('<div style="overflow-y:hidden;color:#FBFBEF"" id="eBLibrary"></div>').dialog(
{
autoOpen: true,
title: 'Browse & Select',
maxWidth: 1000,
maxHeight: 600,
width: 800,
height: 600,
dialogClass: "alertDialog",
modal: true,
buttons: {
"Create an account": libButtons,
Cancel: function () {
dialog.dialog("close");
}
},
closeOnEscape: true,
canMaximize: true,
draggable: true,
resizeHt: 0,
resizeWd: 0,
resizeStop: function (event, ui) {
if (resizeHt == 0 && resizeWd == 0) {
resizeHt = $dlgLibrary.dialog("option", "height");
resizeWd = $dlgLibrary.dialog("option", "width");
};
$('#eBLibrary-Show').width(Number(resizeWd - (resizeWd * 16 / 100))); $('#eBLibrary-Show').height(Number(resizeHt - (resizeHt * 35 / 100)));
resizeHt = 0;
resizeWd = 0;
},
open: function (event, ui) {
var person = {};
person.Name = "Amir";
var pdata = { "p": person };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../../SimpleService.asmx/GetData",
data: JSON.stringify(pdata),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
if (data.hasOwnProperty('d')) {
msg = data.d;
} else {
msg = data;
}
$('#divMore').append(msg);
}
},
error: function (data, status, error) {
alert("error");
}
});
},
close: function (event, ui) {
}
}
);
});
function libButtons() {
var valid = true;
allFields.removeClass("ui-state-error");
valid = valid && checkLength(name, "username", 3, 16);
valid = valid && checkLength(email, "email", 6, 80);
valid = valid && checkLength(password, "password", 5, 16);
valid = valid && checkRegexp(name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter.");
valid = valid && checkRegexp(email, emailRegex, "eg. ui#jquery.com");
valid = valid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");
if (valid) {
$("#users tbody").append("<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
dialog.dialog("close");
}
return valid;
}
</script>
</head>
<body>
</body>
</html>
In a custom button in my pager, I call grid.jqGrid("getGridParam", "data"), "data") to get all the data in the grid but it returns empty array. When I call grid.jqGrid("getGridParam", "data") in the loadComplete function, it still returns an empty array. However if I call grid.jqGrid('getRowData') it gives me the data I am looking for. See my code below.
<%# 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/css/jquery-ui.min.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/css/ui.jqgrid.css"/>
<!-- Overide css styling to ensure that calendar image is inline with text box -->
<style type="text/css">.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;}
</style>
<script src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery-ui.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/grid.locale-en.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<title>Trucks Overview</title>
<script type="text/javascript">
jQuery().ready(function () {
var grid = jQuery("#truck_grid");
var orderGridDialog = $('#truck_grid_dialog');
var gridData;
getUniqueNames = function(columnName) {
var texts = grid.jqGrid('getCol', columnName, false);
var uniqueTexts = [], textsLength = texts.length, text, i, textsMap = {};
for (i=0;i<textsLength;i++) {
text = texts[i];
if (text != undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
uniqueTexts.push(text);
}
}
return uniqueTexts;
};
buildSearchSelect = function(uniqueNames) {
var values=":All";
$.each (uniqueNames, function() {
values += ";" + this + ":" + this;
});
return values;
};
setSearchSelect = function(columnName) {
grid.jqGrid('setColProp', columnName,
{ stype: 'select',
searchoptions: {
value:buildSearchSelect(getUniqueNames(columnName)),
sopt:['eq']
}
}
);
};
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: 'mm/dd/yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
buttonImageOnly: true,
buttonImage: "images/calendar.gif",
buttonText: "Select date",
showButtonPanel: true,
onSelect: function (dateText, inst) {
inst.input.focus();
if (typeof (inst.id) === "string" && inst.id.substr(0, 3) === "gs_") {
$(inst.id).val(dateText);
grid[0].triggerToolbar();
}
else {
// to refresh the filter
$(inst).trigger("change");
}
}
});
}, 100);
};
grid.jqGrid({
url: '${pageContext.request.contextPath}/getTrucksJSONAction',
datatype: "json",
mtype: 'GET',
colNames: ['Truck ID', 'Status', 'Carrier Code', 'Date Created', 'Date Closed', 'T1 Status', 'Truck Arrived'],
colModel: [
{name: 'truckId', key:true, index: 'truckId', align: 'center', width: 100},
{name: 'status', index: 'status', align: 'center', width: 100},
{name: 'carrierName', index: 'carrierName', align: 'center', width: 100},
{name: 'createdDate', index: 'createdDate', align: 'center', width: 100},
{name: 'closedDate', index: 'closedDate', align: 'center', width: 100},
{name: 't1Status', sortable: false, align: 'center', width: 100, fixed: true,
formatter: function (celvalue) {
return celvalue ?
"<img src='http://www.clker.com/cliparts/q/j/I/0/8/d/green-circle-icon-md.png' alt='green light' style='width:15px;height:15px'/>" :
"<img src='http://www.iconsdb.com/icons/preview/red/circle-xxl.png' alt='red light' style='width:10px;height:10px'/>";
}} ,
{name: 'truckArrived', sortable: false, align: 'center', width: 100, fixed: true,
formatter: function (celvalue) {
return celvalue ?
"<img src='http://www.clker.com/cliparts/q/j/I/0/8/d/green-circle-icon-md.png' alt='green light' style='width:15px;height:15px'/>" :
"<img src='http://www.iconsdb.com/icons/preview/red/circle-xxl.png' alt='red light' style='width:10px;height:10px'/>";
}}
],
rowNum: 10,
height: 300,
autoheight: true,
autowidth: true,
rowList: [10, 20, 30],
pager: jQuery('#truck_grid_pager'),
sortname: 'truckId',
sortorder: "desc",
jsonReader: {
root: "records",
page: "page",
total: "total",
records: "rows",
repeatitems: false
},
viewrecords: true,
altRows: false,
gridview: true,
hidegrid: false,
multiselect:true,
recordtext: '',
emptyrecords: 'No Trucks',
forceFit: true,
caption: "Trucks Overview",
loadComplete: function() {
// Reload the grid after changing paginattion
var allRecords = grid.getGridParam('lastpage') * grid.getGridParam('records');
grid.jqGrid('setGridParam', {
recordtext: allRecords + ' Trucks(s) Found. Displaying {0} to {1}'});
$(this).trigger("reloadGrid");
async: false,
setSearchSelect('status');
setSearchSelect('carrierName');
grid.jqGrid('setColProp', 'truckId', {
searchoptions : {
sopt : [ 'bw' ],
dataInit : function(elem) {
$(elem).autocomplete({
source : getUniqueNames('truckId'),
delay : 0,
minLength : 0
});
}
}
});
grid.jqGrid('setColProp', 'createdDate', {
sorttype: 'date', editable: true,
editoptions: { dataInit: initDateWithButton, size: 8 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton
}
});
gridData = $(this).jqGrid("getGridParam", "data");
grid.jqGrid('filterToolbar', {autoSearch: true});
},
}).navGrid('#truck_grid_pager', {edit: false, add: false, del: false, search: false, refresh: true})
.navButtonAdd('#truck_grid_pager', {caption:"Truck Arrived", buttonicon:"ui-icon-flag", position:"first", title:"Truck Arrived",
onClickButton: function(){
var i;
var data = grid.jqGrid("getGridParam", "data");
var selRowIds = grid.jqGrid('getGridParam', 'selarrrow');
for (i = 0; i < data.length; i++) {
if (selRowIds.indexOf(data[i].truckId) > -1) {
data[i].truckArrived = true;
}
}
grid.trigger("reloadGrid");
}
})
.navButtonAdd('#truck_grid_pager', {caption:"Ship Confirm", buttonicon:"ui-icon-circle-check", position:"first", title:"Ship Confirm",
onClickButton: function(){
alert("Ship has been confirmed");}
});
orderGridDialog.dialog({
autoOpen: false,
width: 1000,
height: 400,
draggable: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "blind",
duration: 250
},
close: function(event, ui){
orderGridDialog.text('Loading Grid...');
}
});
});
</script>
</head>
<body>
<table id="truck_grid"></table>
<div id="truck_grid_pager"></div>
<div id="truck_grid_dialog" title="Orders Overview">Loading...</div>
</body>
</html>
The problem happens in the last section of the code, namely:
.navButtonAdd('#truck_grid_pager', {caption:"Truck Arrived", buttonicon:"ui-icon-flag", position:"first", title:"Truck Arrived",
onClickButton: function(){
var i;
var data = grid.jqGrid("getGridParam", "data");
var selRowIds = grid.jqGrid('getGridParam', 'selarrrow');
for (i = 0; i < data.length; i++) {
if (selRowIds.indexOf(data[i].truckId) > -1) {
data[i].truckArrived = true;
}
}
grid.trigger("reloadGrid");
}
})
The second problem I have is when grid.trigger("reloadGrid") is called, the truckArrived icon is not changed from red to green as expected.
The internal parameter data will be used only if one uses datatype: "local". You use datatype: "json". It means that the server hold whole dataset only. The url: '${pageContext.request.contextPath}/getTrucksJSONAction' receive request for the page of sorted and filtered data. The server should implement sorting, filtering/sorting and paging.
There exists a special case: one use remote datatype ("json" or "xml"), but one uses loadonce: true parameter additionally. In the case the server should return all unfiltered data instead of providing the page of data. The returned data should be still sorted corresponds to sortname, sortorder parameter (which will be sent to the server as sidx and sord). jqGrid displays the first page of returned data, but it fills the internal data parameter with whole rows of data returned from the server. After the first loading of data jqGrid changes datatype to "local" and so the later sorting, paging and filtering of data will be like in case of datatype: "local". In the case yoou will be able to get all the data using grid.jqGrid("getGridParam", "data"), but you can do this of case after the data will be once loaded.