jqGrid Add Button and Modal - javascript

When I click the cancel button in the add modal, I get the following error in the jquery.jqGrid.js file:
"0x800a138f - JavaScript runtime error: Unable to get property 'a' of undefined or null reference"
I only get this error in Internet Explorer, Chrome works fine.
The second issue I am having is that I'm calling the add modal from a button:
<button name="addbutton" id="addbutton" class="add-new-row btn btn-success addbutton" style="float:right; margin-top:1%; margin-left:1%;">Add</button>
and then using the following code in the grid JS file:
$(".addbutton").on("click", function () {
$("#grid").editGridRow("new",
{
// add options
//2lines added by Ilango
top: 50, left: 100, width: 500,
addCaption: "Add record Dialog",
addParams: { position: "afterSelected" },//, addRowParams: editOptions
zIndex: 100,
url: "/Transactions/Create",
closeOnEscape: true,
closeAfterAdd: true,
reloadAfterSubmit: true,
afterComplete: function (response) {
if (response.responseText) {
$('#grid').trigger('reloadGrid')
// alert(response.responseText);
//window.location.reload();
//reDefineColWidth();
// $('#grid').trigger('reloadGrid')
window.history.back();
}
},
//submit on enter key
onInitializeForm: function ($form) {
$("td.DataTD>.FormElement", $form).keypress(function (e) {
if (e.which === $.ui.keyCode.ENTER) {
$("#sData", $form.next()).trigger("click");
return false;
}
});
},
//adjust position of add form modal
beforeShowForm: function (form) {
//alert('adding' + "#editmod" + grdNames[0].id);
//var dlgDiv = $("#editmod" + grdNames[0].id);
var dlgDiv = $("#editmod" + $('#grid')[0].id);
//var dlgDiv = jQuery("#editmodgrid");
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
// HINT: change parentWidth and parentHeight in case of the grid
// is larger as the browser window
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
//400 offset from left
dlgDiv[0].style.left = Math.round(parentLeft + 500 + (parentWidth - dlgWidth) / 2) + "px";
},
afterShowForm: function (form) {
//alert('adding' + "#editmod" + grdNames[0].id);
//var dlgDiv = $("#editmod" + grdNames[0].id);
var dlgDiv = $("#editmod" + $('#grid')[0].id);
//var dlgDiv = jQuery("#editmodgrid");
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
// HINT: change parentWidth and parentHeight in case of the grid
// is larger as the browser window
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
//400 offset from left
dlgDiv[0].style.left = Math.round(parentLeft + 500 + (parentWidth - dlgWidth) / 2) + "px";
},
});
});
When I click the submit button, the record is submitted, but only with the default values I have setup for each column, not the values that I entered into the modal. I don't have this issue using the built in navigation add button.
Please help! I've spent many, many hours trying to figure this out.
EDIT:
Here is the block of code where the error occurs if(!h.a):
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
if(A[0]){A.pop();if(!A[0])L('unbind');}
if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
}

Related

How to use window.open to open in same tab (using self does not work)

I have some custom long JS code that is too long to post, basically when user clicks a button on my site, it is creating a custom <form>, and submits it as POST request in a new tab that gets opened.
I want to modify it to open in the same tab. The relevant line of code is:
w = window.open("",'myPop_Window' + wId);
And I've tried changing it to:
w = window.open("",'myPopup_Window' + wId, "_self");
But it didn't work.
I hope this is enough info to figure how can I modify the line to open in same tab.
EDIT:
more code of form creation:
var tryOpenTab2 = function(button,tab_url,tab_url_data_g) {
var data = {};
var form = button.parents('form').first();
if (form.length > 0)
data = getFormData(form);
if (tab_url_data_g) {
data['g'] = tab_url_data_g
}
if (!tab_url)
return;
var form = $('<form></form>');
form.attr('method', 'POST');
form.attr('action', tab_url);
for (var k in data) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', k);
input.attr('value', data[k]);
form.append(input);
}
$('body').append(form);
if (w && !w.closed) {
//w.close();// client want to always open new tab
w = null;
}
wId = ''+new Date().getTime();
w = window.open("",'myPopup_Window' + wId);
form.attr('target', 'myPopup_Window' + wId);
}
EDIT 2:
How shoudl I used wId in new code?
if (button.is(button_class3)) {
w = window.open(window.location.href.split('#')[0] + "#" + button.attr("data-popup-id"));
} else {
wId = ''+new Date().getTime();
if( (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))) {
// w = window.open("",'myPopup_Window' + wId); old line
w = window.open("","_self") // new line 1
form.attr('target', '_self'); // new line 2
}
else { // non mobile agent - use blank
w = window.open('about:blank','myPopup_Window' + wId);
form.attr('target', 'myPopup_Window' + wId);
}
I suspect you can remove tryOpenTab2 from the submitting process and just have the form submit as normal without a target
Else try this
Change
if (w && !w.closed) {
//w.close();// client want to always open new tab
w = null;
}
wId = ''+new Date().getTime();
w = window.open("",'myPopup_Window' + wId);
form.attr('target', 'myPopup_Window' + wId);
to
form.attr('target', '_self');

Client calls server countless times as I close and reopen a pop up

I have a pop up which is opened with Javascript. In this pop up I have a panel that is used for filtering. Every time the user click an option on the Filter and updates the results there is a request sent to the server. However if I close the pop up and reopen it and use the filter again the request will be sent twice and if I keep repeating the same sequence of steps I will continue to increase the requests sent each time by 1.
This is after we open the pop up the first time and filter for first time as you can see there are two request for NarrowEventsSearch
The image below shows what happens after I close the pop up reopen it again and filter inside of it. We can see that there are now 3 requests sent for NarrowEventsSearch
This is the js code that opens the pop up
the function that is called is the following
function tb_show(fake_param, url, callbackFunction) {
SetAjaxCaching(false);
var params = parseThickBoxArgs(url);
trace("----------- Thickbox parameters -----------");
trace("URL Passed was " + url);
trace(params);
var href = params["url"] + "?" + $.param(params);
var dialogTitle = $(this).attr("title");
//Unique id is given for the div
var divId = new Date().getTime().toString();
// Create an anonymous div with a loading gif to be the dialog
var newDiv = $('<div id="' + divId + '" class="dialogcontainer">' + spinnerHTML + '</div>');
// We push the newly created div onto the window stack so we can keep track of what dialogs are open
window.openedDialogs.push([newDiv, href]);
$('body').append(newDiv);
trace("Opening dialog with height " + params["height"] + " and width " + params["width"]);
//To avoid the scrollbars.
var height = parseInt(params["height"]) + 10;
var width = parseInt(params["width"]) + 10;
if (params["percentWidth"] !== undefined) {
var windowWidth = $(window).width();
var percentWidth = parseFloat(params["percentWidth"]) / 100.0;
width = windowWidth * percentWidth;
}
if (params["percentHeight"] !== undefined) {
var windowHeight = $(window).height();
var percentHeight = parseFloat(params["percentHeight"]) / 100.0;
height = windowHeight * percentHeight;
}
var CssClass = params["class"];
if (CssClass == undefined) {
CssClass = '';
}
var title = params["title"];
// Now we actually invoke the dialog function with the parameters we parsed earlier
newDiv.dialog({
title: title,
height: height, //params["height"],
width: width, //params["width"],
closeOnEscape: false,
modal: true,
open: function (event, ui) {
$(this).parent().find('.ui-dialog-titlebar').append("<div style=\"float: right;\"><img src=\"/Resources/Content/Images/Icons/remove.png\" class=\"Delete\" style=\"cursor: pointer;\" onclick=\"closeDialog('" + CssClass + "')\" /></div>");
}
})
.load(href, JSON.stringify({ showLoadingBar: false }), function () {
trace("Overlay Div content loaded");
// After the content has been loaded, apply the thickbox script to the loaded content
applyThickboxes($(this));
// Now run the callback function, if it is indeed a function
if (typeof (callbackFunction) == 'function') {
callbackFunction();
}
});
hideTitleBar();
//LoadValidation();

How do you generate multiple dropdown list boxes in UI App

I have been working with the sample code to allow a user to submit a photo in a google form for update to Google spreadsheet.
I am working with the original code by Serge Insas that I was able to get to work exactly how he intended it to work.
Now I'm trying to work with it to allow for my needs which is simply to have more than one drop down list, I need to capture more information than what the original code allowed for.
I am very new to this and doing most by trial and error.
I can get the form to display with two list boxes but the drop down list of both of them is the same (List1)
Here is the code I've modified, it will post what is selected in the second list box but I need the items from list2 to show up instead.
Any help would be appreciated.
Thanks
var submissionSSKey = '0ArbqJejC7zBydGNUbVpwd2hrQ3RFY3VxZ0RCeU5aV3c';
var docurl = 'https://docs.google.com/document/d/13FWMTtzprlhN73cMp73zPtunsOcoAFO5PCROp1PHiv4/'
var listitems = ['Select a category', 'LKQ', 'AM', 'OEM']
var listitems2 = ['Select a category', 'Wrong Part', 'Poor Fit', 'Poor Quality']
var Panelstyle = {
'background': '#dddddd',
'padding': '40px',
'borderStyle': 'solid',
'borderWidth': '10PX',
'borderColor': '#bbbbbb'
}
function doGet() {
var app = UiApp.createApplication().setTitle('Parts Return Reasons').setStyleAttribute('padding', '50PX');
var panel = app.createFormPanel().setStyleAttributes(Panelstyle).setPixelSize(400, 200);
var title = app.createHTML('<B>PartsReturnReasons</B>').setStyleAttribute('color', 'grey').setStyleAttribute('fontSize', '25PX');
var grid = app.createGrid(7, 2).setId('grid');
var list1 = app.createListBox().setName('list1').setWidth('130');
for (var i in listitems) {
list1.addItem(listitems[i])
}
var list2 = app.createListBox().setName('list2').setWidth('130');
for (var i in listitems2) {
list2.addItem(listitems[i])
}
var Textbox1 = app.createTextBox().setWidth('150px').setName('TB1');
var email = app.createTextBox().setWidth('150px').setName('mail');
var upLoad = app.createFileUpload().setName('uploadedFile');
var submitButton = app.createSubmitButton('<B>Submit</B>');
var warning = app.createHTML('Please fill in all fields').setStyleAttribute('background', '#bbbbbb').setStyleAttribute('fontSize', '18px');
//file upload
var cliHandler2 = app.createClientHandler()
.validateLength(Textbox1, 1, 40).validateNotMatches(list1, 'Select a category').validateEmail(email).validateNotMatches(upLoad, 'FileUpload')
.forTargets(submitButton).setEnabled(true)
.forTargets(warning).setHTML('Now you can submit your form').setStyleAttribute('background', '#99FF99').setStyleAttribute('fontSize', '12px');
//Grid layout of items on form
grid.setWidget(0, 1, title)
.setText(1, 0, 'Category')
.setWidget(1, 1, list1.addClickHandler(cliHandler2))
.setText(2, 0, 'Reason')
.setWidget(2, 1, list2.addClickHandler(cliHandler2))
.setText(3, 0, 'Name')
.setWidget(3, 1, Textbox1.addClickHandler(cliHandler2))
.setText(4, 0, 'Email')
.setWidget(4, 1, email)
.setText(5, 0, 'Image File')
.setWidget(5, 1, upLoad.addChangeHandler(cliHandler2))
.setWidget(6, 0, submitButton)
.setWidget(6, 1, warning);
var cliHandler = app.createClientHandler().forTargets(warning).setHTML('<B>PLEASE WAIT WHILE THE FILE IS UPLOADING<B>').setStyleAttribute('background', 'yellow');
submitButton.addClickHandler(cliHandler).setEnabled(false);
panel.add(grid);
app.add(panel);
return app;
}
function doPost(e) {
var app = UiApp.getActiveApplication();
var ListVal1 = e.parameter.list1;
var ListVal2 = e.parameter.list2;
var textVal = e.parameter.TB1;
var Email = e.parameter.mail;
var fileBlob = e.parameter.uploadedFile;
var blob = fileBlob.setContentTypeFromExtension()
var img = DocsList.createFile(blob);
try {
var folder = DocsList.getFolder('photos');
} catch (e) {
DocsList.createFolder('photos');
var folder = DocsList.getFolder('photos')
}
img.addToFolder(folder);
img.removeFromFolder(DocsList.getRootFolder());
var weight = parseInt(img.getSize() / 1000);
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheetByName('Sheet1');
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow + 1, 1, 1, 5).setValues([
[ListVal1, ListVal2, textVal, Email, "https://drive.google.com/uc?export=view&id=" + img.getId()]
]);
var imageInsert = sheet.getRange(lastRow + 1, 5).setFormula('=image("https://drive.google.com/uc?export=view&id=' + img.getId() + '")');
sheet.setRowHeight(lastRow + 1, 80);
var GDoc = DocumentApp.openByUrl(docurl)
GDoc.appendTable([
['Category : ' + ListVal1, ListVal2, 'Name : ' + textVal, 'Email : ' + Email]
])
var inlineI = GDoc.appendImage(img);
var width = inlineI.getWidth();
var newW = width;
var height = inlineI.getHeight();
var newH = height;
var ratio = width / height;
Logger.log('w=' + width + 'h=' + height + ' ratio=' + ratio);
if (width > 640) {
newW = 640;
newH = parseInt(newW / ratio);
}
inlineI.setWidth(newW).setHeight(newH)
GDoc.appendParagraph('IMAGE size : ' + width + ' x ' + height + ' (eventually) resized to ' + newW + ' x ' + newH + ' for PREVIEW (' + weight + ' kB) ');
GDoc.appendHorizontalRule();
GDoc.saveAndClose();
app.add(app.createLabel('Thank you for submitting'));
return app;
}
You made a simple typo in your code.
for (var i in listitems2) { list2.addItem(listitems2[i])
You have to take items for list in the right source array

How to create a function to center windows

I'm using the jqgrid, and to focus the popup to add, delete and edit, I need to use the parameter beforeShowForm that before this show window, shows the center of the screen. The problem is I have to always do the same code for these three functions.
The function is as follows:
{ // edit option
beforeShowForm: function(form) {
var dlgDiv = $("#editmod" + $(this)[0].id);
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth-dlgWidth )/2 ) + "px";
}
},
In order to reuse the same code, I would create a separate function to be always writing the same amount of code. I tried to create the following function:
Function:
function test(dlgDiv)
{
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth-dlgWidth )/2 ) + "px";
}
In Grid:
{ // edit option
beforeShowForm: function(form) {
var dlgDiv = $("#editmod" + $(this)[0].id);
test(dlgDiv);
}
},
But continued without giving. Says that the value dlgDiv is not defined. Does anyone know how to solve this?
The issue lies in the selector you use here:
var dlgDiv = $("#editmod" + $(this)[0].id);
Whatever element you're trying to get isn't being returned, because the selector can't find it. You should revise your selector to reflect the ID of the element you're attempting to find.
If you've done that and you still have an issue, the problem lies with your context and this doesn't mean what you think it means in the above line of code. You'll have to show us more code before I can elaborate on that, though.

vtip jQuery to display titles

I am using vTip plugin to display titles on hover , here is my example code:
http://jsfiddle.net/bnjSs/
I have a Div#showTitles , When i click on it I wants to toggle display of all div.vtips titles on page just like mouseover.
$("#showTitles").click(function(){
// this I am not sure how to acheive.
return false;
});
UPDATE:
http://jsfiddle.net/bnjSs/2/
I have tried this but its not showing on correct positions as mouseover but once i mouseover on .vtip and then i click on #showTitles its working fine, I also need to toggle this behavior :
$("#showTitles").click(function(e,ui){
this.xOffset = 5;
this.yOffset = 10;
this.top = (e.pageY + yOffset);
this.left = (e.pageX + xOffset);
$('.vtip').each(function(index) {
title = $(this).text();
$('body').append( '<p id="vtip"><img id="vtipArrow" />' + title + '</p>' );
$('p#vtip #vtipArrow').attr("src", 'images/vtip_arrow.png');
$('p#vtip').css("top", this.top+"px").css("left",
this.left+"px").fadeIn("slow");
});
return false;
});
Thanks for any help.
IDs should be unique.finished
I've modified your current code to get it work under the current conditions. The function logic should be obvious because of the descriptive names. Fiddle: http://jsfiddle.net/bnjSs/7/
Update: Added show/hide text + feature to the code, as requested at the comments.
Update2: Taken care of whole code, improved efficiency.
You're overusing this. this.xOffset = 5 attaches xOffset to the element. Use var xOffset = 5 to define xOffset in the scope of the function. The code below has the following scope model:
$(document).ready(function(){
// Variables defined using `var` can be read by
// any function defined within this function
function vtip(){
// variables declared here can be read by any function defined inside vtip
// but cannot be read by methods outside vtip
function(){..} at .hover and .mousemove
// These functions also have an own scope, and variables defined using
// var cannot be read by anything outside these functions, even at vtip
$("#showTitles").click(function(e){
// variables declared here cannot be read by code outside this function
// This function can read any variable which is declared using var at
// $(document).ready
Note: "Declare" means "Define using var".
Final code:
// Run when the DOM is ready
//Note: $(function(){ is short for $(document).ready(function(){
$(function(){
var xOffset = 5; // x distance from mouse
var yOffset = 10; // y distance from mouse
var frozen_vtip = false; //Define it
var vtip = function() {
$(".displaytip").unbind().hover(
function(e) {
if(frozen_vtip) return;
this.t = this.title;
this.title = '';
var top = (e.pageY + yOffset);
var left = (e.pageX + xOffset);
$('<p class="vtip"><img class="vtipArrow" src=""/>' + this.t + '</p>').css("top", top+"px").css("left", left+"px").fadeIn("slow").appendTo(this);
},
function() {
if(frozen_vtip) return;
this.title = this.t;
$("p.vtip", this).fadeOut("slow").remove();
}
).mousemove(
function(e) {
if(frozen_vtip) return;
var top = (e.pageY + yOffset);
var left = (e.pageX + xOffset);
$("p.vtip", this).css("top", top+"px").css("left", left+"px");
}
);
};
vtip();
// Second function, when text is "Hide titles" it should
// prevent runing vtip() on mouseover (above function) and
// when text is "Show titles" It should normally run vtip()
// (mouseover display title.
$("#showTitles").click(function(e){
e.preventDefault();
if($(this).text() == "Hide titles"){
$(this).text("Show titles");
$('p.vtip').fadeOut("slow").remove();
$('.displaytip').each(function(){
this.title = this.t; //Re-attach `title`
});
frozen_vtip = false;
} else {
frozen_vtip = true;
$(this).text("Hide titles");
$('.displaytip').each(function(index) {
if($('p.vtip', this).length) {return;}
this.t = this.title;
this.title = '';
var $this = $(this);
var offset = $this.offset();
var height = $this.height();
var top = offset.top + height;
var left = offset.left + height;
$('<p class="vtip"><img class="vtipArrow" src="images/vtip_arrow.png" />' + this.t + '</p>' ).appendTo(this).css("top", top+"px").css("left", left+"px").fadeIn("slow");
});
}
});
});

Categories