Using Twitter bootstrap modal instead of confirm dialog

Ayhan picture Ayhan · Aug 31, 2012 · Viewed 20.4k times · Source

I am trying to use twitter bootstrap modal instead of custom confirm dialog.

my function

function getConfirm(confirmMessage){
    if ( confirmMessage == undefined){
        confirmMessage = '';
    }
    $('#confirmbox').modal({
    show:true,
        backdrop:false,
        keyboard: false,
    });

    $('#confirmMessage').html(confirmMessage);
    $('#confirmFalse').click(function(){
        $('#confirmbox').modal('hide');
        return false;
    });
    $('#confirmTrue').click(function(){
        $('#confirmbox').modal('hide');
        return true;
    });
}   
</script>
<div class="modal" id="confirmbox" style="display: none">
    <div class="modal-body">
        <p id="confirmMessage">Any confirmation message?</p>
    </div>
    <div class="modal-footer">
        <button class="btn" id="confirmFalse">Cancel</button>
        <button class="btn btn-primary" id="confirmTrue">OK</button>
    </div>
</div>

calling the function

var confimChange=getConfirm("Do You confirm?");
if(confimChange){
    alert('perfect you confirmed')
}else{
    alert('why didnt you confirmed??')
}

the problem is getConfirm function is not returning true or false.


WORKING CODE:

if(receiverListCount > 0){
    var confimChange=confirm("Message");
    if(confimChange){
        resetReceiverList();
    }else{
        return false;
    }
}

code piece after modifications & changes /not working

if(activeDiv == '#upload'){
    if(listOfSelectedGroups.length> 0|| receiverListCount > 0){
        getConfirm("message",function(result){
            if(result){
                resetReceiverList();
            }else{
                return false;
            }
        });
    }
}

finaly I decided to use bootboxjs

Answer

Lloyd picture Lloyd · Aug 31, 2012

Your approach is wrong, it will execute kind of asynchronously so that it won't wait for the modal dialog to be closed before returning. Try something like this:

function getConfirm(confirmMessage,callback){
    confirmMessage = confirmMessage || '';

    $('#confirmbox').modal({show:true,
                            backdrop:false,
                            keyboard: false,
    });

    $('#confirmMessage').html(confirmMessage);
    $('#confirmFalse').click(function(){
        $('#confirmbox').modal('hide');
        if (callback) callback(false);

    });
    $('#confirmTrue').click(function(){
        $('#confirmbox').modal('hide');
        if (callback) callback(true);
    });
}  

getConfirm('Are you sure?',function(result) {
   // Do something with result...
});

Note however you only really need to initialize the modal once and hook the events once. I'd give the modal body and ID and simply change the content before showing.

You should also set backdrop to true, you want a confirmation to prevent the user from accessing the page until they confirm.