Search code examples
javascriptjqueryconfirm

Getting a custom prompt box to return true or false


I am attempting to code a custom javascript confirmation box. At the click of the [OK] button, the dialog box should a true value and at the click of the [CANCEL] button, the dialog box should return a false value. However, it seems that the alert box fires prematurely, and that when I click the buttons, nothing happens.

function test() {

var btn1 = "<br><br><input type='button' class='button' value='OK' onclick='function(){ return true}'>"
var btn2 = "<br><br><input type='button' class='button' value='CANCEL' onclick='function(){ return false}'>"

var x = ShowDialog(false,"Test",btn1 + btn2)

alert(x)

}

Ive made a fiddle:


Solution

  • First of all you can't have a custom dialog in javascript that blocks execution the way alert does. Actually the one you're trying to implement is confirm(). It is a system function provided by browser. It returns true or false depending on which button was clicked.

    However the only way you can do your custom popup using html is to do it asynchronously. Thus you should call ShowDialog and provide a callback to it. It will be called when user clicks one of the buttons. Any code that exists after call to ShowDialog will be called immediately. And all code that you want to process the result of the dialog should be placed inside the callback

    var btn1 = "<br><br><input type='button' class='button' value='OK' x-data='true'>"
    var btn2 = "<br><br><input type='button' class='button' value='CANCEL' x-data='false'>"
    ShowDialog(false, "Test", btn1 + btn2, undefined, function(result){
        alert(result)
    })
    
    function ShowDialog(modal, title, text, colour, callback) {
        ...
        $('input', '#dialog_text').click(function(){
            if(typeof callback === 'function'){
                callback($(this).attr('x-data'));
            }
            HideDialog();
        });
    }
    

    Edited fiddle