Si o No confirmar cuadro usando jQuery


Quiero alertas sí/No usando jQuery, en lugar del botón ok / Cancel:

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

¿Alguna otra alternativa?

Author: Tshepang, 2010-08-19

8 answers

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();
        }
    });
};

Por favor, encuentre la Demo .

 107
Author: Thulasiram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-02 18:52:05

El método alert bloquea la ejecución hasta que el usuario la cierra:

Utilice la función confirmar:

if (confirm('Some message')) {
    alert('Thanks for confirming');
} else {
    alert('Why did you press cancel? You should have confirmed');
}
 91
Author: Ana El Bembo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-26 18:49:10

He usado estos códigos:

HTML:

<a id="delete-button">Delete</a>
[2]} 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>

Estos códigos funcionan para mí, pero no estoy realmente seguro de si esto es apropiado. ¿Qué opinas?

 39
Author: user3678239,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-02 23:47:03

Echa un vistazo a este plugin de jQuery: jquery.confirmar.

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

Y luego:

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

Esto mostrará una ventana emergente de confirmación antes de seguir el enlace.

Aquí hay una demo: http://myclabs.github.com/jquery.confirm /

 28
Author: Matthieu Napoli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-28 11:40:50

Todos los ejemplos que he visto no son reutilizables para diferentes preguntas de tipo "sí/no". Estaba buscando algo que me permitiera especificar una devolución de llamada para poder llamar por cualquier situación.

Lo siguiente está funcionando bien para mí:

$.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");
}
});

Entonces lo llamo así:

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

$.confirm(
    "CONFIRM", //title
    "Delete " + filename + "?", //message
    "Delete", //button text
    deleteOk //"yes" callback
);
 10
Author: MSquared,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-13 07:52:47

Tuve problemas para obtener la respuesta del cuadro de diálogo, pero finalmente se me ocurrió una solución combinando la respuesta de esta otra pregunta display-yes-and-no-buttons-instead-of-ok-and-cancel-in-confirm-box con parte del código del diálogo de confirmación modal

Esto es lo que se sugirió para la otra pregunta:

Crea tu propio cuadro de confirmación:

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

Crea tu propio método confirm():

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();
}

Llámelo por su código:

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

MIS CAMBIOS He ajustado lo anterior para que en lugar de llamar confirmBox.show() usé confirmBox.dialog({...}) así

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();
          }
        }
    });

El otro cambio que hice fue crear el div confirmBox dentro de la función doConfirm, como hizo ThulasiRam en su respuesta.

 1
Author: J F,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:32

Necesitaba aplicar una traducción a los botones Aceptar y Cancelar. Modifiqué el código para except dynamic text (llama a mi función de traducción)


$.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);
    }
});
 0
Author: Jim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-22 15:44:18

Puede reutilizar su confirmación:

    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);
 -2
Author: thamaht,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-09 00:42:33