ASP.NET Post-Back and window.onload - javascript

I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks

When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}

Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}

Related

Disable a table cell after the first click in javascript

I have a table cell as the following :
<td id=report onMouseUp='clickReport()' onKeyPress='clickReport()' >Click</td>";
The event function is as below :
function clickReport() {
document.form.submit();
}
On form submission, there is a back-end process going on. Until the 1st process completes(i.e., until the page reloads), I do not want the user to press the press the "Click" again, else it may affect the previous running process.
So, I thought of disabling the "Click" after the first press.
I tried using preventDefault() but it is not working.
function clickReport() {
document.form.submit();
document.getElementById("report").onMouseUp = function(e)
{
e.preventDefault();
return false;
}
document.getElementById("report").onKeyPress = function(e)
{
e.preventDefault();
return false;
}
}
Can someone please help!
1) You might pass the element parameter to your event functions, so you can acces the DOM element easily. See below.
<td id=report onMouseUp='clickReport(this)' onKeyPress='clickReport(this)' >Click</td>";
2) On the first function run you might null the events, so they will not fire anymore. See below.
// the *element* parameter is yor <td> element here
function clickReport(element) {
document.form.submit();
element.onMouseUp = null;
element.onKeyPress= null;
}
3) You might use onclick event instead of onmouseup and get rid of onkeypress, if you only want to make it work on click.
<td id=report onclick='clickReport(this)'>Click</td>";
function clickReport(element) {
document.form.submit();
element.onclick= null;
}
Working codepen: https://codepen.io/anon/pen/MmVNMe
this should work.
since at first the disableClick is undefined the click will fire, as soon as it fires the flag will be set to true and the click will no longer be possible.
<td id=report onMouseUp='!disableClick && clickReport()'
onKeyPress='!disableClick && clickReport()' >Click</td>"
function clickReport() {
document.form.submit();
window.disableClick = true;
}

Can't make sens out of javascript event and functions

Here is the code that works as-is, a classic onBeforeUnLoad event, in the <script type="text/jscript"> tag of my ASP page :
window.onbeforeunload = function (e) {
a = 1;
e = e || window.event;
e.preventDefault = true;
e.cancelBubble = true;
e.returnValue = "do you wish to save?";
}
Now, two issues i'm experiencing when wanting to do something more complex :
I want this to appear only once at all cost :
var a = 0;
window.onbeforeunload = function (e) {
if (a == 0) {
a = 1;
e = e || window.event;
e.preventDefault = true;
e.cancelBubble = true;
e.returnValue = "Wish to save?";
}
}
//Does not work...
I want it to be able to run this other function that works when not combined with the first :
comfirmExit = function(){
if (confirm("Wish to save?") == true) {
document.getElementById('<%= btnEnregistrer.ClientID %>').click();
}
}
// works, but not when combine to the first function
I tried to put this all together... I want the unload event to make my confirm box function run :
window.onbeforeunload = function (e) {
if (a == 0) {
a = 1;
comfirmExit = function(){
if (confirm("Wish to save?") == true) {
document.getElementById('<%= btnEnregistrer.ClientID %>').click();
}
}
}
And now I realize I'm far from being an expert of javascript...
The beforeunload event won't run any obtrusive Javascript for the user (ie alert, confirm etc).
But there is an workaround, the steps should be something like:
Create a boolean flag to check if the user has canceled the exiting of your page (default false).
Create the beforeunload event handler, and check if the game is not
saved.
If it was already saved, then, you do nothing, and let the user go
But if it was not, then you change that boolean flag to true.
You keep an interval dirty-checking if that variable is true, and at anytime it is, you save the game for the user, and then set this variable to false again.
So, doing that, you'll ensure the user always see a message if they're leaving without saving, and if they cancel the exiting, the game will be automatically saved, making the next try pretty smooth.
Take a look at the example below. To test it, open your console, click on Run. Then, try to click on Run again, and you'll see an exiting message. If you confirm it, your console won't show anything. But if you cancel it, then, you'll be kept in the page, then you try to click Run again, and you'll see that no message will appear, but the console will log true.
(function() {
var game = { saved: false };
var canceled = false;
setInterval(function() {
if (canceled) {
game.saved = true;
canceled = false;
}
}, 100);
window.onbeforeunload = function() {
if (!game.saved) {
canceled = true;
return 'Are you sure?';
}
else {
console.log(game.saved);
}
}
})();

redirect to other page if click on leave page

How can i redirect him if a user clicks on leave a page button on onbeforeunload. Please check my code
function openNewWindow() {
window.open('http://google.com/','_blank');
window.focus();
}
window.onbeforeunload = function(event) {
event = event || window.event;
var confirmClose = 'Are you sure?';
if (event) {
event.returnValue = confirmClose;
if(confirmClose)
{
if(true)
{
openNewWindow();
}
}
return confirmClose;
}
}
Thanks
If the users chooses yes in the onbeforeunload dialog then he will leave the page, you can not prevent this. You can however do some things before the dialog shows, like you are doing in your code, but the dialog it self is only displayed AFTER your function executes, displaying the return value.
Your code seems a bit obscure to, what are you expecting from if(confirmClose), this will always evaluate to true because a non empty string is "truthy" in javascript.

Can you pause a form submission and then restart

Without using any JS libraries, is it possible to pause a form submission, run some code and then restart it?
Reason I ask is that I currently have a form that when it submits runs code that sends a request to my analytics provider. Works fine in Chrome/IE but in Firefox and Safari there is a drop out of these analytics of 60%.
The feeling is that the submission follows through before the scripts execute, hence why we are trying to pause the submit event.
Interested to hear any thoughts or insight.
You can use the submit event to cancel the form submission, do your analytics ajax stuff, and then submit the form programmatically using the submit method on the form element.
For example (live copy):
HTML:
<form id="theForm" action="#" method="GET">
<label>Field: <input type="text" name="theField"></label>
<br><input type="submit" value="Submit">
</form>
JavaScript:
window.onload = function() {
var form, counter;
form = document.getElementById("theForm");
form.onsubmit = function() {
if (typeof counter === "undefined") {
display("Starting count down (" + counter + ")");
counter = 3;
setTimeout(delayedSubmit, 1000);
}
display("Cancelling form submit");
return false;
};
function delayedSubmit() {
if (typeof counter === "number") {
--counter;
if (counter > 0) {
display("Continuing count down (" + counter + ")");
setTimeout(delayedSubmit, 1000);
}
else {
display("Count down complete, submitting form");
counter = undefined;
form.submit();
}
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
};
There I've used a count down timer rather than an ajax operation, but the principle is the same.
Off-topic: I've used the old DOM0 style of setting up an event handler there (form.onsubmit = ...). I don't recommend it, but it keeps the example simple. Setting up event handlers is one of the places where a library like jQuery, Prototype, YUI, Closure, or any of several others can smooth over browser differences (and provide added functionality) for you, it's well worth considering using one.
Just place a button in place of the submit button that runs the analytics script as a function, then submit the form with
document.forms["myform"].submit();
See this site How to submit a form through javascript.
Hope that helps.
You can listen to the submit event. Something like:
(function() {
var processed = false;
form.onsubmit = function(event) {
event = event || window.event;
if(!processed) {
if(event.preventDefault) { // cancel default action
event.preventDefault();
}
else {
event.returnValue = false;
}
// run your code
// execute the next two lines in a callback if necessary
processed = true;
form.submit();
}
};
}());
You need to attach the function to run on event "onsubmit", return a false from the event handler if you want to cancel the form submission, or use below:
function onSubmitHandler(evnt){
//run some code set some flag
if(flag is set) evnt.preventDefault(); else return true;
}

DropDownList not firing onbeforeunload when AutoPostBack="True"

I have implemented an "unsaved changes" warning using techniques described on these pages:
Client/JS Framework for "Unsaved Data" Protection?
http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
This works well except for a DropDownList on the page. It does an AutoPostBack, and I want onbeforeunload to fire because unsaved changes will be lost, but it isn't working. Should it be raising the onbeforeunload event? Can I somehow make it raise the event?
Edit:
The DropDownList is inside an UpdatePanel, so that means it isn't unloading the page and that would be why onbeforeunload isn't being triggered. Is there any way I can trigger the event programmatically? Or do I have to roll my own imitation Confirm dialog?
Edit2
I now have a solution that adds the dialog to asynchronous postbacks from an UpdatePanel. I have edited the original script, adding the call to setConfirmAsyncPostBack() as described in my solution.
Here is my JavaScript:
/****Scripts to warn user of unsaved changes****/
//https://stackoverflow.com/questions/140460
//http://jonstjohn.com/node/23
//Activates the confirm message onbeforeunload.
function setConfirmUnload(on) {
setConfirmAsyncPostBack();
if (on) {
removeCheckFromNoWarnClasses();
fixIEonBeforeUnload();
window.onbeforeunload = unloadMessage
return;
}
window.onbeforeunload = null
}
function unloadMessage() {
return 'You have unsaved changes.';
}
//Moves javascript from href to onclick to prevent IE raising onbeforeunload unecessarily
//http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
function fixIEonBeforeUnload() {
if (!$.browser.msie)
return;
$('a').filter(function() {
return (/^javascript\:/i).test($(this).attr('href'));
}).each(function() {
var hrefscript = $(this).attr('href');
hrefscript = hrefscript.substr(11);
$(this).data('hrefscript', hrefscript);
}).click(function() {
var hrefscript = $(this).data('hrefscript');
eval(hrefscript);
return false;
}).attr('href', '#');
}
//Removes warnings from Save buttons, links, etc, that have been can be given "no-warn" or "no-warn-validate" css class
//"no-warn-validate" inputs/links will only remove warning after successful validation
//use the no-warn-validate class on buttons/links that cause validation.
//use the no-warn class on controls that have CausesValidation=false (e.g. a "Save as Draft" button).
function removeCheckFromNoWarnClasses() {
$('.no-warn-validate').click(function() {
if (Page_ClientValidate == null || Page_ClientValidate()) {
setConfirmUnload(false);
}
});
$('.no-warn').click(function() {
setConfirmUnload(false);
});
}
//Adds client side events to all input controls to switch on confirmation onbeforeunload
function enableUnsavedChangesWarning() {
$(':input').one('change', function() {
window.onbeforeunload = function() {
return 'You have unsaved changes.';
}
});
removeCheckFromNoWarnClasses();
}
And in my ASP.NET page, when the user makes a change:
if (changed)
{
...
//Confirm unload if there are unsaved changes.
//NB we also have to call fixIEonBeforeUnload() to fix links, done in in page load to include links that are rendered during callbacks
ScriptManager.RegisterStartupScript(Page, GetType(), "unsavedchanges", "setConfirmUnload(true);", true);
}
else
...
Also see How to prevent AutoPostBack when DropDownlist is selected using jQuery
//http://msdn.microsoft.com/en-us/magazine/cc163413.aspx
//https://stackoverflow.com/questions/2424327/prevent-asp-net-dopostback-from-jquery-submit-within-updatepanel
//Adds an event handler to confirm unsaved changes when an asynchronous postback is initialised by an UpdatePanel
function setConfirmAsyncPostBack() {
if (typeof (Sys.WebForms) === "undefined" || typeof (Sys.WebForms.PageRequestManager) === "undefined")
return;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(confirmAsyncPostBack);
}
//An event handler for asynchronous postbacks that confirms unsaved changes, cancelling the postback if they are not confirmed
//Adds the confirmation to elements that have a css class of "warn"
function confirmAsyncPostBack(sender, args) {
if (window.onbeforeunload != null && args.get_postBackElement().className == "warn" && !unloadConfirmed())
args.set_cancel(true);
}
//Displays a confirmation dialog that imitates the dialog displayed by onbeforeunload
function unloadConfirmed() {
var confirmed = confirm("Are you sure you want to navigate away from this page?\n\n" + unloadMessage() + "\n\nPress OK to continue or Cancel to stay on the current page.");
if (confirmed)
window.onbeforeunload = null;
return confirmed;
}

Categories