Yes or No confirm box using jQuery
Asked Answered
N

9

143

I want yes/No alerts using jQuery, instead of ok/Cancel button:

jQuery.alerts.okButton = 'Yes';
jQuery.alerts.cancelButton = 'No';                  
jConfirm('Are you sure??',  '', function(r) {
    if (r == true) {                    
        //Ok button pressed...
    }  
}

Any other alternatives?

Necessarian answered 19/8, 2010 at 8:10 Comment(7)
Dupe, #3166536Pervade
Have a look at the jQuery UI: jqueryui.com/demos/dialog/#modal-confirmationIntuitionism
or #3166059Ming
this posted code works? what shall i replace 'jQuery' with? its not working for me...i guess i shall use $ but how? whats the syntaxAllistir
$.alerts.okButton = ' Yes '; $.alerts.cancelButton = ' No '; jConfirm('Are you sure??', '', function(r) { if (r == true) { //Ok button pressed... } }Necessarian
Another JQuery Dialog solution more like a confirm() function which returns: https://mcmap.net/q/56222/-jquery-deferred-and-dialog-box Hope this helpsSaucepan
#3520361Pozsony
P
146

ConfirmDialog('Are you sure');

function ConfirmDialog(message) {
  $('<div></div>').appendTo('body')
    .html('<div><h6>' + message + '?</h6></div>')
    .dialog({
      modal: true,
      title: 'Delete message',
      zIndex: 10000,
      autoOpen: true,
      width: 'auto',
      resizable: false,
      buttons: {
        Yes: function() {
          // $(obj).removeAttr('onclick');                                
          // $(obj).parents('.Parent').remove();

          $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');

          $(this).dialog("close");
        },
        No: function() {
          $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');

          $(this).dialog("close");
        }
      },
      close: function(event, ui) {
        $(this).remove();
      }
    });
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
Pozsony answered 25/5, 2012 at 11:29 Comment(3)
is this jquery-ui or plain old jquery? I don't see .dialog() anywhere on jQuery's documentaiton.Camus
u need to include jquery and jquery ui script in your page.Pozsony
@Pozsony how can I add the plugin in yii2 framework ?Vesica
P
145

The alert method blocks execution until the user closes it:

use the confirm function:

if (confirm('Some message')) {
    alert('Thanks for confirming');
} else {
    alert('Why did you press cancel? You should have confirmed');
}
Postbellum answered 26/8, 2013 at 18:49 Comment(1)
confirm is "OK CANCEL" though, not "YES NO".Trichina
P
75

I've used these codes:

HTML:

<a id="delete-button">Delete</a>

jQuery:

<script>
$("#delete-button").click(function(){
    if(confirm("Are you sure you want to delete this?")){
        $("#delete-button").attr("href", "query.php?ACTION=delete&ID='1'");
    }
    else{
        return false;
    }
});
</script>

These codes works for me, but I'm not really sure if this is proper. What do you think?

Psychoneurotic answered 21/7, 2014 at 8:29 Comment(1)
More shorter return confirm("Are you sure you want to return this meter?") ))Hewet
B
28

Have a look at this jQuery plugin: jquery.confirm.

<a href="home" class="confirm">Go to home</a>

and then:

$(".confirm").confirm();

This will show a confirmation popup before proceeding to following the link.

There's a demo here: http://myclabs.github.com/jquery.confirm/

Bojorquez answered 28/3, 2013 at 11:40 Comment(0)
T
13

All the example I've seen aren't reusable for different "yes/no" type questions. I was looking for something that would allow me to specify a callback so I could call for any situation.

The following is working well for me:

$.extend({ confirm: function (title, message, yesText, yesCallback) {
    $("<div></div>").dialog( {
        buttons: [{
            text: yesText,
            click: function() {
                yesCallback();
                $( this ).remove();
            }
        },
        {
            text: "Cancel",
            click: function() {
                $( this ).remove();
            }
        }
        ],
        close: function (event, ui) { $(this).remove(); },
        resizable: false,
        title: title,
        modal: true
    }).text(message).parent().addClass("alert");
}
});

I then call it like this:

var deleteOk = function() {
    uploadFile.del(fileid, function() {alert("Deleted")})
};

$.confirm(
    "CONFIRM", //title
    "Delete " + filename + "?", //message
    "Delete", //button text
    deleteOk //"yes" callback
);
Thusly answered 13/2, 2013 at 7:11 Comment(0)
M
6

I had trouble getting the answer back from the dialog box but eventually came up with a solution by combining the answer from this other question display-yes-and-no-buttons-instead-of-ok-and-cancel-in-confirm-box with part of the code from the modal-confirmation dialog

This is what was suggested for the other question:

Create your own confirm box:

<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>

Create your own confirm() method:

function doConfirm(msg, yesFn, noFn)
{
    var confirmBox = $("#confirmBox");
    confirmBox.find(".message").text(msg);
    confirmBox.find(".yes,.no").unbind().click(function()
    {
        confirmBox.hide();
    });
    confirmBox.find(".yes").click(yesFn);
    confirmBox.find(".no").click(noFn);
    confirmBox.show();
}

Call it by your code:

doConfirm("Are you sure?", function yes()
{
    form.submit();
}, function no()
{
    // do nothing
});

MY CHANGES I have tweaked the above so that instead of calling confirmBox.show() I used confirmBox.dialog({...}) like this

confirmBox.dialog
    ({
      autoOpen: true,
      modal: true,
      buttons:
        {
          'Yes': function () {
            $(this).dialog('close');
            $(this).find(".yes").click();
          },
          'No': function () {
            $(this).dialog('close');
            $(this).find(".no").click();
          }
        }
    });

The other change I made was to create the confirmBox div within the doConfirm function, like ThulasiRam did in his answer.

Mob answered 2/7, 2012 at 15:4 Comment(0)
C
1

Try This... It's very simple just use confirm dialog box for alert with YES|NO.

if(confirm("Do you want to upgrade?")){ Your code }

Choreography answered 30/7, 2020 at 6:54 Comment(0)
M
0

I needed to apply a translation to the Ok and Cancel buttons. I modified the code to except dynamic text (calls my translation function)


$.extend({
    confirm: function(message, title, okAction) {
        $("<div></div>").dialog({
            // Remove the closing 'X' from the dialog
            open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
            width: 500,
            buttons: [{
                text: localizationInstance.translate("Ok"),
                click: function () {
                    $(this).dialog("close");
                    okAction();
                }
            },
                {
                text: localizationInstance.translate("Cancel"),
                click: function() {
                    $(this).dialog("close");
                }
            }],
            close: function(event, ui) { $(this).remove(); },
            resizable: false,
            title: title,
            modal: true
        }).text(message);
    }
});
Microfarad answered 22/4, 2015 at 15:44 Comment(0)
A
-3

You can reuse your confirm:

    function doConfirm(body, $_nombrefuncion)
    {   var param = undefined;
        var $confirm = $("<div id='confirm' class='hide'></div>").dialog({
            autoOpen: false,
            buttons: {
                Yes: function() {
                param = true;
                $_nombrefuncion(param);
                $(this).dialog('close');
            },
                No: function() {
                param = false;
                $_nombrefuncion(param);
                $(this).dialog('close');
            }
                                    }
        });
        $confirm.html("<h3>"+body+"<h3>");
        $confirm.dialog('open');                                     
    };

// for this form just u must change or create a new function for to reuse the confirm
    function resultadoconfirmresetVTyBFD(param){
        $fecha = $("#asigfecha").val();
        if(param ==true){
              // DO THE CONFIRM
        }
    }

//Now just u must call the function doConfirm
    doConfirm('body message',resultadoconfirmresetVTyBFD);
Avoidance answered 9/8, 2014 at 0:28 Comment(1)
Please, use correct English and avoid abbreviations like "u". Also, it is better if you can explain a little bit your code to illustrate and educate the OP, and why you think your answer is better than any of the previously posted.Astri

© 2022 - 2024 — McMap. All rights reserved.