[javascript] jQuery UI Alert Dialog as a replacement for alert()

I'm using alert() to output my validation errors back to the user as my design does not make provision for anything else, but I would rather use jQuery UI dialog as the alert dialog box for my message.

Since errors are not contained in a (html) div, I am not sure how to go about doing this. Normally you would assign the dialog() to a div say $("#divName").dialog() but I more need a js function something like alert_dialog("Custom message here") or something similiar.

Any ideas?

This question is related to javascript jquery jquery-ui alert jquery-ui-dialog

The answer is


I took @EkoJR's answer, and added an additional parameter to pass in with a callback function to occur when the user closes the dialog.

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: onCloseCallback
    });
}

You can then call it and pass it a function, that will occur when the user closes the dialog, as so:

jqAlert('Your payment maintenance has been saved.', 
        'Processing Complete', 
        function(){ window.location = 'search.aspx' })

Use this code syntax.

   $("<div></div>").html("YOUR MESSAGE").dialog(); 

this works but it append a node to the DOM. You can use a class and then or first remove all elements with that class. ex:

function simple_alert(msg)
{
    $('div.simple_alert').remove();
    $('<div></div>').html(is_valid.msg).dialog({dialogClass:'simple_alert'});
}

Building on eidylon's answer, here's a version that will not show the title bar if TitleMsg is empty:

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!outputMsg) return;

    var div=$('<div></div>');
    div.html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: onCloseCallback
    });
    if (!titleMsg) div.siblings('.ui-dialog-titlebar').hide();
}

see jsfiddle


DAlert jQuery UI Plugin Check this out, This may help you


There is an issue that if you close the dialog it will execute the onCloseCallback function. This is a better design.

function jAlert2(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": onCloseCallback,
            "Cancel": function() {
          $( this ).dialog( "destroy" );
            }

        },
    });

Using some of the info in here I ended up creating my own function to use.

Could be used as...

custom_alert();
custom_alert( 'Display Message' );
custom_alert( 'Display Message', 'Set Title' );

jQuery UI Alert Replacement

function custom_alert( message, title ) {
    if ( !title )
        title = 'Alert';

    if ( !message )
        message = 'No Message to Display.';

    $('<div></div>').html( message ).dialog({
        title: title,
        resizable: false,
        modal: true,
        buttons: {
            'Ok': function()  {
                $( this ).dialog( 'close' );
            }
        }
    });
}

Just throw an empty, hidden div onto your html page and give it an ID. Then you can use that for your jQuery UI dialog. You can populate the text just like you normally would with any jquery call.


As mentioned by nux and micheg79 a node is left behind in the DOM after the dialog closes.

This can also be cleaned up simply by adding:

$(this).dialog('destroy').remove();

to the close method of the dialog. Example adding this line to eidylon's answer:

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: function() { onCloseCallback();
                           /* Cleanup node(s) from DOM */
                           $(this).dialog('destroy').remove();
                          }
    });
}

EDIT: I had problems getting callback function to run and found that I had to add parentheses () to onCloseCallback to actually trigger the callback. This helped me understand why: In JavaScript, does it make a difference if I call a function with parentheses?


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to alert

Swift alert view with OK and Cancel: which button tapped? Bootstrap Alert Auto Close How to reload a page after the OK click on the Alert Page How to display an alert box from C# in ASP.NET? HTML - Alert Box when loading page How to show an alert box in PHP? Twitter Bootstrap alert message close and open again How to handle login pop up window using Selenium WebDriver? How to check if an alert exists using WebDriver? chrome undo the action of "prevent this page from creating additional dialogs"

Examples related to jquery-ui-dialog

Error: TypeError: $(...).dialog is not a function jQuery UI Dialog - missing close icon jquery ui Dialog: cannot call methods on dialog prior to initialization jQuery dialog popup jQuery UI Alert Dialog as a replacement for alert() How to display an IFRAME inside a jQuery UI dialog How can I disable a button on a jQuery UI dialog? Detect if a jQuery UI dialog box is open How to close jQuery Dialog within the dialog? How to completely remove a dialog on close