How can I implement a confirmation dialog for critical action? - javascript

Im not proficient in JS myself very much, so it would probably take me a few hours to figure this out myself, so I figured I'd ask you guys.
I have Delete/Ban links on my site, that are used by admins to moderate the users and what they post. Since these links have such drastic consequences on the site's content I would want to have some sort of confirmation that would popup when one of the links is clicked.
It should have some extra text explaining what's about to happen, and OK/Cancel buttons.
So I have a link, for example like this:
Ban John
Delete Post
When this link is clicked, the code needs to be triggered. If OK is pressed, it goes to ban.php?id=123, if Cancel is pressed, it doesn't go anywhere.
A simple JS dialog box, will do. Or if you have a link for a fancy jquery powered box, you can point me towards that also.
Thanks!

Easiest way to achieve this is to use the confirm() function:
var confirmed = confirm('Do you really want to do this?');
if(confirmed) {
//Do dangerous action
}
It basically displays a box with the text you provide and ok and cancel buttons.
With a link you can do something like this:
<a href="someurl" onclick="return confirm('Are you sure?');">
It's not best possible practices to put the action in the onclick like that, but it works and is simple to understand even if you're not a pro javascripter

I think you're looking for something like "confirm delete".
The Confirm function takes as an input a string parameter. It displays a dialog box whose message is that parameter, with OK and Cancel buttons.
If the user clicks OK, the confirm function returns True; if the user clicks Cancel False is returned.
Here's an example of using it:
function fConfirmDelete()
{
if(confirm("Delete Field?"))
{
document.forms[0].lblFieldSelect.value="DELETE";
document.forms[0].submit();
}
else
{
document.forms[0].lblFieldSelect.value="";
}
return;
}

Here's a decent jQuery dialog plugin. Of course, you will need jQuery too.
http://nadiana.com/jquery-confirm-plugin

var confirm = confirm('Blabla');
if(confirm)
{
// do
}

This is plain JS:
<a href="delete.do"
onClick="return confirm('Delete. Are you sure?');">Delete</a>

Looking for this?
//Cleaner explanation
$("document").ready(function(){
$(".dangerousLink").each(function(){
var confirmUrl = $(this).attr('href');
$(this).attr('href', 'javascript:;');
$(this).click(function(){
if(confirm("This is dangerous... are you sure?")) {
window.location = confirmUrl;
}
});
});
});
//Now just append a class dangerousLink to all links that you want confirmation
Blow up
If you are looking for a fancy dialog, you'll find something interesting here.

Related

How to create JS function that will confirm the submission of the form, when not all fields are completed

I was wondering how to create a function in JS/JQuery that upon clicking submit button (if some fields are not completed) the confirmation pop-out will show up, and if users clicks NO the POST method won't work. I'am pretty stucked... XD
well you can try something like add class to all the form fields you want to make sure that are not empty and then run something like this.
$(document).ready(function(){
var flag = ture;
$("yourButton").click(function(){
$(".myclass").each(function(){
if($(this).val() == '') flag = false;
})
if(!flag) {// do what ever}
})
})
something like this.
again your question is a bit "big" cos we got nothing to work with.
gl.
Perhaps what you're looking for is just jQuery Validation.
You can check their demo page to see some example and learn how to use it.

Remove a Leave button using javascript [duplicate]

I have the following beforeunload function which I have stolen from sonewhere else....
$().ready(function() {
$("#posManagerLoginForm").trigger("submit");
$(window).bind("beforeunload", function(){
window.setTimeout(function () {
window.location = "home.htm";
}, 0);
window.onbeforeunload = null; // necessary to prevent infinite loop that kills your browser
return "Press 'Stay On Page' to go to Reporting Manager home";
});
});
Regardless of what option I select I get navigated to home.htm. Is there a way that I can make the dialog box an ok button instead of the default "Leave Page" or "Stay on page" options?
Or perhaps someone else could make a suggestion on hot to better handle?
thanks
You cannot override the styling of the onbeforeunload dialog. Believe me, I tried this before in my earlier projects.
Reference: http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx
It is built into the browser object, and you have no control over it.
You can however set your own dialog to show when the onbeforeunload event triggers, but it will not disable that the regular one will show. Quite annoying, yes.
The reason you're still getting redirected is because you're actually doing nothing to prevent it.
If you want to open an alert box before the form gets submitted, make sure the default behaviour is prevented (which is to submit the form), then redirect after OK has been clicked like this:
$().ready(function() {
$("#posManagerLoginForm").submit(function( event ) {
event.preventDefault();
alert("Press 'OK' to go to Reporting Manager home");
window.location = "home.htm";
});
});
Though not sure what the use of this would be. If you wanted to stay on the form if a different button is pressed (say 'Cancel' for example), then you'd rather want to use a 'confirm' like this:
$().ready(function() {
$("#posManagerLoginForm").submit(function( event ) {
event.preventDefault();
if confirm(("Press 'OK' to go to Reporting Manager home"))
window.location = "home.htm";
});
});
You could replace the alert or confirm with a custom dialog box too, depending on what library you're using. Just make sure you put window.location = "home.htm" inside the dialog's function, otherwise it will execute immediately.
As an example, you may want to have a look into jQuery UI's dialog here: https://jqueryui.com/dialog/

Dialog pop up box

I would like to make register button, but when people click on it. A pop up dialog will appear and has two button for user to click. One is YES , One is NO. IF they select YES, will pass them to X page. Convert way, they select NO, will pass them to Y page. I search on google but only OK and cancel confirm.
YES --> VIP REGISTER
NO --> REGULAR REGISTER
Should i use Jquery?
You can use jQuery UI for this.
$('<div>', {text: 'Do you have VIP code?'}).dialog({
modal: true,
buttons: {
'Yes': function() {
window.location = ...;
},
'No': function() {
window.location = ...;
}
}
});
Note that this dialog box will by default include a "close" button and will also close automatically if you press escape. You need to either disable those features (see here for how), or decide what action to take (if any) when that happens.
You can do this in classic javascript
var answer = confirm ("Do you have vip code?")
and then treat the answer accordingly
You can use the built-in confirm method if you don't want to customise the look-and-feel of the dialog (you can't change anything, including the text of the buttons):
if (confirm("Do you have VIP code?")) {
//Yes!
} else {
//No
}
If you want to customise the dialog, look at the endless lightbox scripts that are available. As mentioned by #Alnitak, jQuery UI provides a good one.
jquery is a good way to do this very easy. But often the problem is, people belive they can use jQuery without understanding Javascript itself. So, first learn the basics of Javascript (for Example: Methodchaning, Closurs, Array-Handling, Prototyping) and after that try jQuery. The Box you want is very easy to do with jQuery-UI and
window.location = "vip.html";

jQuery Exit Popup Redirect?

So I've been looking around for hours, testing multiple versions, testing some of my own theories and I just can't seem to get it working.
What I'm trying to do is use alert or confirm (or whatever works) so popup a dialog when a user tries to navigate away from a purchase form. I just want to ask them "Hey, instead of leaving, why not get a free consultation?" and redirect the user to the "Free Consultation" form.
This is what I have so far and I'm just not getting the right results.
$(window).bind('beforeunload', function(){
var pop = confirm('Are you sure you want to leave? Why not get a FREE consultation?');
if (pop) {
window.location.href('http://www.mydomain/free-consultation/');
} else {
// bye bye
}
});
$("form").submit(function() {
$(window).unbind("beforeunload");
});
This is showing confirm dialog to user, want to stay or leave page. Not exactly what you looking for but maybe it will be useful for start.
function setDirtyFlag() {
needToConfirm = true; //Call this function if some changes is made to the web page and requires an alert
// Of-course you could call this is Keypress event of a text box or so...
}
function releaseDirtyFlag() {
needToConfirm = false; //Call this function if dosent requires an alert.
//this could be called when save button is clicked
}
window.onbeforeunload = confirmExit;
function confirmExit() {
if (needToConfirm)
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
Script taken from http://forums.devarticles.com/showpost.php?p=156884&postcount=18
Instead of using the beforeunload and alert(), I decided to check whether or not the users mouse has left the document. See code below:
$(document).bind('mouseleave', function(event) {
// show an unobtrusive modal
});
Not sure whether it will help.
You need to stop the propagation before showing the Confirm / Alert.
Please refer http://jonathonhill.net/2011-03-04/catching-the-javascript-beforeunload-event-the-cross-browser-way/
Look at the last comment.
Try this:
window.onunload = redirurl;
function redirurl() {
alert('Check this Page');
window.location.href('http://www.google.com');
}

Gmail-style Exit Message

I realize this is likely a duplicate, but I've been googling/SOing for a day now and I can't find a satisfactory answer. If there is an answer already on SO, please send me there.
I have a client that insists on having an exit message popup confirming they want to exit the site, just like Gmail does. (I've already tried arguing against it. He is immovable, so no comments about how that is bad practice please.)
I've found this code:
<script>
window.onbeforeunload = function() {
return 'Are you sure you want to exit?';
}
<script>
But it runs no matter what I do - reloading the page, clicking on the nav, etc.
I just want the message to show up when the user closes the tab/browser. I suspect it's something simple I'm missing but I'm not a Javascript expert.
Any help would be greatly appreciated.
Thanks
EDIT
Here's what is working pretty good. Thanks to all!
var isLeavingSite = true;
//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
isLeavingSite = false;
});
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):
var isLeavingSite = true;
//This would be called on each link/button click that navigates
function GlobalLinkHandler()
{
isLeavingSite = false;
}
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
If you're using jQuery, you can use the code below to flip the isLeavingSite flag:
$('a, input[type="submit"]').click(function(){ isLeavingSite = false; });
What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the onbeforeunload event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.
You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the onbeforeunload event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.
If your using jQuery try this Confirm before exit

Categories