Ad

Custom Confirm Button With Promise Jquery

- 1 answer

i'm trying to create a custom confirm pop up in jquery, i made a function that shows the custom alert when requested with inside a text and two buttons: ok, cancel.:

function showprompt(content){
   $("#confirm").css("display","block");
   $("#msg").text(content); 
}

The problem is that how i can wait until the button clicked and get back the result, if ok so return true? i was thinking that i need to use promise and defer. How i can do?

I don't like to use precreated confirm buttons with plugins JQuery UI - Dialog

Ad

Answer

A promise is a great idea for this type of functionality (they're not only for async!). Let's say you have two buttons inside of #confirm are called #ok and #cancel.

This is how it would look:

function showprompt(content) {
   var dfd = $.Deferred();

   $('#confirm').css('display','block')
   $('#msg').text(content);

   $('#confirm')
     //turn off any events that were bound to the buttons last 
     //time you called showprompt()
     .off('click.prompt') 

      //resolve the deferred
     .on('click.prompt','#ok',function() { dfd.resolve(); }) 

      //reject the deferred
     .on('click.prompt','#cancel',function() { dfd.reject(); });

   //return a the deferred's promise
   return dfd.promise();
}

Then you'd use it like this:

showprompt(content).then(
   function() { alert('You clicked ok'); }, //promise resolved
   function() { alert('You clicked cancel'); }, //promise rejected
);
Ad
source: stackoverflow.com
Ad