Alert with multiple options - javascript

Just wondering, is it possible to create an alert with multiple options?
Like for example, in Facebook, when you try to close the tab/window when you have not finished typing your message, an alert with the options "Leave this page" and "Stay on this page" will pop up.

Example with form, you'are looking for window.onbeforeunload:
<script type="text/javascript">
var originalFormContent
var checkForChanges = true;
jQuery(document).ready(function () {
originalFormContent = jQuery('#myForm input[type=text]').serialize() + jQuery('#myForm select').serialize();
});
function onClose() {
if (checkForChanges && originalFormContent != "undefined") {
var content = jQuery('#myForm input[type=text]').serialize() + jQuery('#myForm select').serialize();
if (content != originalFormContent) {
return confirm('You have unsaved changes. Click OK if you wish to continue ,click Cancel to return to your form.');
}
}
}
window.onbeforeunload = onClose();

You're referring to window.onbeforeunload:
Best way to detect when a user leaves a web page?
You can also use the window.confirm() function for OK/Cancel options:
http://jsfiddle.net/UFw4k/1
Other than that, you'd have to implement a custom modal alert, such as jQuery Dialog.

Please have a look at http://jqueryui.com/dialog/#default
Copied this from a previous answer: JavaScript alert with 3 buttons

Related

How to hide keyboard after submitting a form that asks for confirmation

I am trying to get a form which asks for input and then asks the user to confirm it before proceeding. I am having an issue with iPhone 5 where the keyboard doesn't disappear after the user presses return, and the keyboard covers the confirmation window.
I've used the solution posted on another question (the solution is to blur the input) to get the keyboard to disappear on most pages. However, in this case, the "Confirm" dialogue shows up before the input is blurred, regardless of when I call the hideKeyboard function.
This is the code:
<form name="pay" method="POST" onsubmit="hideKeyboard(); return doSubmit('Are you sure you want to transfer', $('#amount'));" action="{{link_to_next_step}}">
var hideKeyboard = function() {
document.activeElement.blur();
$("input").blur();
};
function doSubmit(text1, text2, form) {
hideKeyboard();
$('input:text').each(function() {
var value = $(this).val();
$(this).val(value.replace(/\,/i, '.'));
});
if (isNaN(parseFloat($('input:text').val()))) {
document.getElementById('err_zero').style.display = 'block';
return false;
} else if (confirm(text1 + parseFloat($('input:text').val()).toFixed(2))) {
return true;
} else {
return false;
}
}
Any help is appreciated.
Edit: I've checked similar answers, and making the keyboard disappear is not the problem I'm having. The issue is that the code to deselect the input field only runs after the "Confirm" dialogue is resolved.

Exit-pop Javascript setup on WP site with CF7 on particular events

I got some buttons on a website "www.domain.com":
some a href plain text links like "Click Here to request Callback"
some img wrapped in a hrefs to pop-up a Contact Form 7 forms
Contact Form 7 forms with Submit buttons
and I got an Exit-pop script which works if user clicks X button to close the window. This script just asks something like "Are you sure? We got and special offer and click CANCEL" and than he is redirected to special offer page "www.domain.com/sale/".
But problem is if user Orders something 3) he is still got special discount offer! And the logic is - if he click a button 1) or 2) (callback or just button to popup CF7 form but not Submited an order in CF7) it is OK to run a JavaScript for him, and if he entered his phone in CF7 Order form and successfully Submitted it ("on_sent_ok" event for example mb?) he is done and no need to give him an discount offer JavaScript. And of course somehow it should detect that if user on "www.domain.com/sale/" page the script should don’t fire up to prevent double offering.
I got this script on some forum, but:
First it doesn't fun after 1) and 2) buttons hit (even if a user hit "Order" but that he didn't submitted it and just leave the site). And second it is still fires on "www.domain.com/sale/" page.
The script:
<script language="javascript">
(function() {
setTimeout(function() {
var __redirect_to = 'http://domain.com/sale/';
var _tags = ['button', 'input', 'a'], _els, _i, _i2;
for(_i in _tags) {
_els = document.getElementsByTagName(_tags[_i]);
for(_i2 in _els) {
if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit' && _els[_i2].type != 'image') || _els[_i2].target == '_blank') continue;
_els[_i2].onclick = function() {window.onbeforeunload = function(){};}
}
}
window.onbeforeunload = function() {
setTimeout(function() {
window.onbeforeunload = function() {};
setTimeout(function() {
document.location.href = __redirect_to;
}, 500);
},5);
return 'WAIT BEFORE YOU GO! CLICK THE *CANCEL* BUTTON RIGHT NOW! PAGE. I HAVE SOMETHING VERY SPECIAL FOR YOU COMPLETELY FREE.';
}
}, 500);
})();
</script>

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.

How can I prevent a page unload with jQuery?

In my program, if a user tries to leave a page, he'll receive a dialog box asking if he is sure he wants to leave.
How should I implement the 'cancel' option if the user chooses not to leave the page?
Source javascript code:
$(window).unload(function(){
var c= confirm ("Are you sure?");
if (c){
alert("Thanks. Good luck!");
}
else{
????
}
});
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
many question about this in stackoverflow
How can I override the OnBeforeUnload dialog and replace it with my own?
JavaScript + onbeforeunload
jQuery(window).on('beforeunload',function(){
var value = navigateAway(isDirty);
if(value=="changed")`enter code here`
{
if(jQuery("#saveCheck").val()=="false")
{
return "<?php echo JText::_('OVR_WANT_TO_LEAVE');?>";
}
}
});

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