Alert with multiple options
Asked Answered
G

4

6

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.

Gallman answered 28/3, 2014 at 10:17 Comment(3)
possible duplicate of JavaScript alert with 3 buttonsWhitnell
@Whitnell But you can't name confirm() options.Gallman
@Whitnell Then how did the creator of the Facebook site do it? How did he give the alert two options that have names besides "Ok" and "Cancel"?Gallman
M
5

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(); 

Meredi answered 28/3, 2014 at 10:28 Comment(0)
O
4

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.

Obtect answered 28/3, 2014 at 10:24 Comment(0)
O
0

Please have a look at http://jqueryui.com/dialog/#default

Copied this from a previous answer: JavaScript alert with 3 buttons

Odo answered 28/3, 2014 at 10:23 Comment(1)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.Chamness
Y
0

A little late, but you can use the beforeunload event.

window.addEventListener("beforeunload", function (ev) {
    ev.preventDefault();
})
Yockey answered 2/5, 2024 at 12:23 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.