JQuery confirmation dialog
Asked Answered
V

7

8

I am looking for an way to implement a reusable "confirm" Dialog with JQuery..

This is the part from the MyApp Class to open the dialog:

/**
 * @param text string Message to display
 */
getConfirmationDialog: function(text) {
   MyApp.confirmDialog = $('<div><p>' + text + '</p></div>');
   MyApp.confirmDialog
    .dialog({
        modal: true,
        autoOpen: false,
        title: 'Please confirm',
        width: 300,
        height: 180,
        buttons: {
            'OK': function() {
                return true;
            },
            Cancel: function() {
                $(this).dialog('close');
                return false;
            }
        }
    });

    MyApp.confirmDialog.dialog('open');
},

In another class I do:

/**
 * Clear system cache
 *
 * @param url string Backend URL
 */
clearCache: function(url) {

    dialog = MyApp.getConfirmationDialog('Clear cache?');

    //dialog returns true..
    if (dialog) {
        MyApp.admin.dashboard.doClearCache();
    }

},

But I have no idea to do this the "right" way.. the dialog can't return an value or?

Vitellin answered 12/12, 2010 at 15:54 Comment(0)
T
3

jQuery ui does not provide a nice way to change the dialog button events.

I would use a pubsub pattern, tiny pubsub plugin from Cowboyba here or phiggins effort here. It is cleaner than trying to use the jquery ui getters and setters to try to change the buttons and their click events and if you making a large app will help you in lots of other places.

You can publish the event for the clicking of the ok button and then subscribe and unsubscribe other handlers to listen to the event.

Quick Demo here to show functionality.

Transpadane answered 12/12, 2010 at 16:39 Comment(2)
you made my day :-) it is hard to think about "events" when you come from php development!Vitellin
@ArneRie great stuff, hope you enjoy the new way of doing things in jquery:) Good vid here from Rebecca about pubsub blog.rebeccamurphey.com/pubsub-screencastTranspadane
D
5

The code below is my solution to this problem. I documented usage within the function but will emphasize it here:

$.ConfirmDialog('Do you want to continue?', 'Continue Title', function() { alert('yes'); }, function() { alert('no'); }, null);

No special setup required, just include the "ConfirmDialog" codeblock on your page (I put mine in my app.js) and call with the single line above. Enjoy!

$.ConfirmDialog = function (message, title, callbackYes, callbackNo, callbackArgument) {
    /// <summary>
    ///     Generic confirmation dialog.
    ///
    ///     Usage:
    ///         $.ConfirmDialog('Do you want to continue?', 'Continue Title', function() { alert('yes'); }, function() { alert('no'); }, null);
    ///         $.ConfirmDialog('Do you want to continue?', 'Continue Title', function(arg) { alert('yes, ' + arg); }, function(arg) { alert('no, ' + arg); }, 'please');
    ///</summary>
    ///<param name="message" type="String">
    ///     The string message to display in the dialog.
    ///</param>
    ///<param name="title" type="String">
    ///     The string title to display in the top bar of the dialog.
    ///</param>
    ///<param name="callbackYes" type="Function">
    ///     The callback function when response is yes.
    ///</param>
    ///<param name="callbackNo" type="Function">
    ///     The callback function when response is no.
    ///</param>
    ///<param name="callbackNo" type="Object">
    ///     Optional parameter that is passed to either callback function.
    ///</param>

    if ($("#modalConfirmDialog").length == 0)
        $('body').append('<div id="modalConfirmDialog"></div>');

    var dlg = $("#modalConfirmDialog")
        .html(message)
        .dialog({
            autoOpen: false, // set this to false so we can manually open it
            dialogClass: "confirmScreenWindow",
            closeOnEscape: true,
            draggable: false,
            width: 460,
            minHeight: 50,
            modal: true,
            resizable: false,
            title: title,
            buttons: {
                Yes: function () {
                    if (callbackYes && typeof (callbackYes) === "function") {
                        if (callbackArgument == null) {
                            callbackYes();
                        } else {
                            callbackYes(callbackArgument);
                        }
                    }

                    $(this).dialog("close");
                },

                No: function () {
                    if (callbackNo && typeof (callbackNo) === "function") {
                        if (callbackArgument == null) {
                            callbackNo();
                        } else {
                            callbackNo(callbackArgument);
                        }
                    }

                    $(this).dialog("close");
                }
            }
        });
    dlg.dialog("open");
};
Dropkick answered 3/4, 2012 at 19:13 Comment(0)
S
4
  1. Create confirm class.

    //Below is the confirmation Class skeleton

       function ConfirmDialog() {
           this.showMessage = function(message, callback, argument) {
    
                var $dialog = $('<div></div>')
                   .html(message)
                   .dialog({
                        modal: true,
                        closeOnEscape: true,
                        buttons: {
                             Yes: function() {
                               if (callback && typeof(callback) === "function") {
                                  if (argument == 'undefined') {
                                      callback();
                                   } else {
                                      callback(argument);
                                    }
                                  }
    
                                 $(this).dialog("close");
                               },
    
                              No: function() {
                                  $(this).dialog("close");
                              }
                          }
                      });
                  $dialog.dialog("open");
                 }
           }
    
  2. Create object of type confirmDialog and place in .jsp

    CONFIRM_DIALOG = new ConfirmDialog();
    
  3. Create a callback message with one param.

    function saved(what) {
        alert("Saved: " + what);        
    }
    
  4. Call it where ever you need it.

    CONFIRM_DIALOG.showMessage("Do you wish to marry?", saved, "Life");
    

Job Done!!

Schizogenesis answered 20/9, 2011 at 15:58 Comment(1)
I've looked at 'sweetalert2', and some others, but this is the simplest implementation if you're already running jquery-ui; just what I was looking for.Volant
S
4

See vinay's answer above for the confirm buttons. I reused it to create a simple yet reusable dialog with an ok button for normal purposes and ok n cancel for confirmation. You may also set a custom title and content on the fly.

<div id="yeah" title="Alert">
    <p id="yeah_msg">&nbsp;</p>
</div>

<button id="click_me">Show it</button>

<script type="text/javascript">
    function dlg(msg, callback, title){
        if(callback == undefined){
            callback = null;
        }
        if(title == undefined){
            title = 'Alert';
        }

        $("#yeah_msg").html(msg);
        $("#yeah").dialog('option', 'title', title);

        if(callback){
            $("#yeah").dialog('option', 'buttons', { 
                "Ok": function() { 
                    $( this ).dialog( "close" );
                    if(null != callback) callback.success();
                }, 
                'Cancel': function(){
                    $( this ).dialog( "close" );
                    if(null != callback) callback.fail();
                }  
            });
        }else{
            $("#yeah").dialog('option', 'buttons', { 
                "Ok": function() { 
                    $( this ).dialog( "close" );
                }
            });
        }

        $("#yeah").dialog("open");
    }

    $(document).ready(function(){
        //create dialog
        $("#yeah").dialog({ 
            autoOpen: false, 
            modal: true, 
            show: 'blind', 
            hide: 'explode',
            resizable: false 
        });

        //show dialog   
        $('#click_me').click(function(){
            dlg('title', {success: function(){ console.log('yipee'); }, fail: function(){ console.log('nopee'); } });
        });
    });
</script>
Seagoing answered 13/10, 2012 at 14:41 Comment(0)
T
3

jQuery ui does not provide a nice way to change the dialog button events.

I would use a pubsub pattern, tiny pubsub plugin from Cowboyba here or phiggins effort here. It is cleaner than trying to use the jquery ui getters and setters to try to change the buttons and their click events and if you making a large app will help you in lots of other places.

You can publish the event for the clicking of the ok button and then subscribe and unsubscribe other handlers to listen to the event.

Quick Demo here to show functionality.

Transpadane answered 12/12, 2010 at 16:39 Comment(2)
you made my day :-) it is hard to think about "events" when you come from php development!Vitellin
@ArneRie great stuff, hope you enjoy the new way of doing things in jquery:) Good vid here from Rebecca about pubsub blog.rebeccamurphey.com/pubsub-screencastTranspadane
S
2

I think I get what you're saying. Take a look at my jsfiddle attempt and see if it helps you out at all. I think it is doing what you're trying.

Summarize answered 12/12, 2010 at 16:33 Comment(0)
S
1

I have successfully implemented the confirmation box in Jquery. make sure that you have the Jquery library and css INCLUDED in your code before trying this( jquery-ui-1.8.16.custom.css, jquery-1.6.2.js,jquery-ui-1.8.16.custom.min.js). The MAIN DIFFERENCE BETWEEN JAVASCRIPT CONFIRM BOX AND THIS BOX THAT WE CREATE USING DIV - IS THAT - JAVASCRIPT CONFIRM WILL WAIT FOR USER INPUT, AFTER USER ENTERS YES/NO THE NEXT LINE WILL EXECUTE, HERE YOU HAVE TO DO THAT IN YES, OR NO BLOCK --**THE NEXT LINE OF CODE AFTER THE showConfirm() will execute immediately* so be careful

/** add this div to your html

*/

var $confirm;
var callBack;
var iconStyle = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>';
var messageStyleStart = '<span align="center" style="font-family:arial, verdana, sans-serif;font-size:9.3pt;">';
var messageStyleEnd = '</span>';


$(document).ready(function(){
    $('#confirmDialog').dialog({
            autoOpen: false,
            modal: true
    });


    //jquery confirm box -- the general alert box
    $confirm = $('<div  style="vertical-align:middle;"></div>')
    .html('This Message will be replaced!')
    .dialog({
        autoOpen: false,
        modal: true,
        position: 'top',
        height:300,
        width: 460,
        modal: true,
        buttons: {
            Ok   : function() {
                $( this ).dialog( "close" );
                if(null != callBack)
                    callBack.success();
            },
            Cancel: function() {
                $( this ).dialog( "close" );
                if(null != callBack)
                    callBack.fail();
            }
        }
    }); 

});

    function showConfirm(message,callBackMe,title){
    callBack = null;
    $confirm.html(""); // work around
    $confirm.html(iconStyle + messageStyleStart +message + messageStyleEnd);
    if(title =='undefined'|| null ==title)
        $confirm.dialog( "option", "title", "Please confirm" );
    else
        $confirm.dialog( "option", "title", title);
    var val = $confirm.dialog('open');
    callBack = callBackMe;
    // prevent the default action
    return true;
}

    // Now for calling the function 
// create a Javascript/jSOn callback object 

var callMeBack = {
                    success: function()
                            {   // call your yes function here                                  
                                clickedYes();
                                return;
                            },
                    fail: function (){
                                // call your 'no' function here
                                 clickedNo();
                                return ;
                            }
                };


    showConfirm("Do you want to Exit ?<br/>"+
                    ,callMeBack1,"Please Answer");
Sennet answered 24/1, 2012 at 0:4 Comment(0)
B
1

Whoa why is this so complex? Here is an easy way

$("#myButton").click(function(event) {
    var cont = confirm('Continue?');
    if(cont) {
        // do stuff here if OK was clicked
        return true;
    }
    // If cancel was clicked button execution will be halted.
    event.preventDefault();
}
Benenson answered 13/12, 2012 at 21:34 Comment(1)
because i need an well looking confirm dialog, not the default one ;)Vitellin

© 2022 - 2024 — McMap. All rights reserved.