Wednesday, June 5, 2013

Jquery UI Modal Dialog Confirmation, Return Value

well lets start by the fact that u cant, the modal is a void, it doent return anything.
but then again god gave the JS creators the though to give us Callbacks!! problems solved!
just make ur "big" function a 2-3-x part.

lets start with the confirm code, I did it very generic and u can always add/remove:
 

function custom_confirm(output_msg, title_msg, okBtnText, cancelBtnText, ok_callback, cancel_callback) {
  if (!title_msg)
      title_msg = 'Alert';
  $("<div></div>").html(output_msg).dialog({
      title: title_msg,
     
resizable: false,
      modal: true,
      buttons: [{ 
          text: okBtnText,
         
click: function () {
             $(this).dialog("destroy"); 
             if (ok_callback){
                 ok_callback();

             }
          }
       }, {
          text: cancelBtnText,
         
click: function () {
             $(this).dialog("destroy");
             if (cancel_callback){
                 
cancel_callback();
             }
          }
      }]
  });
}
 


the Callbacks r just simple functions like:
function myOkCallback() {
   alert('I DID IT!! I DID A CALLBACK IN JS!!');
}
and more Callbacks for each extra button, so u have the calling function and the callbacks, like with ajax.

p.s. to us noobs:
custom_confirm(output_msg, title_msg, okBtnText, cancelBtnText,
function() { some code... }, function() { some code... })

2 comments:

  1. Great post, 10x

    ReplyDelete
  2. I would have written:
    if(ok_callback) ok_callback()

    And same for cancel callback

    This way you have "overloads" without callbacks

    ReplyDelete