2009-12-03 11 views
7

¿Cómo puedo lograr esto?¿La forma más fácil de crear un mensaje de confirmación con jQuery/JavaScript?

  1. Un usuario hace clic en el enlace eliminar (con una clase de "confirmar").
  2. Aparece un mensaje de confirmación que pregunta "¿Está seguro?" con las opciones "Sí" y "Cancelar".

Si se selecciona Sí, el enlace continúa como se hizo clic, pero si se selecciona cancelar, la acción se cancela.

Actualización: código de trabajo final con confirm() gracias a this guy:

$('.confirm').click(function() { 
    return confirm("Are you sure you want to delete this?"); 
}); 
+0

lo pusiste en un ready $ (document)() {}? – helloandre

+0

Sí, está en mi documento listo. – Andrew

Respuesta

17

Javascript proporciona un diálogo de confirmación de orden interna.

if (confirm("Are you sure?")) 
{ 
    // continue with delete 
} 
+0

Le dará opciones de Aceptar y Cancelar. –

+0

no se puede superar por la facilidad. – nickf

+0

La respuesta más simple suele ser la correcta :) – AntonioCS

0

Implementé con éxito el cuadro de confirmación en Jquery. asegúrese de tener la biblioteca Jquery y css INCLUIDOS en su código antes de intentar esto (jquery-ui-1.8.16.custom.css, jquery-1.6.2.js, jquery-ui-1.8.16.custom.min. js). La DIFERENCIA PRINCIPAL ENTRE JAVASCRIPT CONFIRM BOX Y ESTA CAJA QUE CREAMOS USANDO DIV - ES QUE - JAVASCRIPT CONFIRMA ESPERA LA ENTRADA DEL USUARIO, DESPUÉS DE QUE EL USUARIO INGRESE SÍ/NO LA SIGUIENTE LÍNEA EJECUTARÁ, AQUÍ DEBE HACER ESO EN SÍ, O NO BLOCK - ** la siguiente línea de código después de la showConfirm() se ejecutará inmediatamente * así que tenga cuidado

/** add this div to your html 

*/

var $confirm; 
var callBack; 
var iconStyle = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>'; 
var messageStyleStart = '<span align="center" style="font-family:arial, verdana, sans-serif;font-size:9.3pt;">'; 
var messageStyleEnd = '</span>'; 


$(document).ready(function(){ 
    $('#confirmDialog').dialog({ 
      autoOpen: false, 
      modal: true 
    }); 


    //jquery confirm box -- the general alert box 
    $confirm = $('<div style="vertical-align:middle;"></div>') 
    .html('This Message will be replaced!') 
    .dialog({ 
     autoOpen: false, 
     modal: true, 
     position: 'top', 
     height:300, 
     width: 460, 
     modal: true, 
     buttons: { 
      Ok : function() { 
       $(this).dialog("close"); 
       if(null != callBack) 
        callBack.success(); 
      }, 
      Cancel: function() { 
       $(this).dialog("close"); 
       if(null != callBack) 
        callBack.fail(); 
      } 
     } 
    }); 

}); 

    function showConfirm(message,callBackMe,title){ 
    callBack = null; 
    $confirm.html(""); // work around 
    $confirm.html(iconStyle + messageStyleStart +message + messageStyleEnd); 
    if(title =='undefined'|| null ==title) 
     $confirm.dialog("option", "title", "Please confirm"); 
    else 
     $confirm.dialog("option", "title", title); 
    var val = $confirm.dialog('open'); 
    callBack = callBackMe; 
    // prevent the default action 
    return true; 
} 

    // Now for calling the function 
// create a Javascript/jSOn callback object 

var callMeBack = { 
        success: function() 
          { // call your yes function here         
           clickedYes(); 
           return; 
          }, 
        fail: function(){ 
           // call your 'no' function here 
           clickedNo(); 
           return ; 
          } 
       }; 


    showConfirm("Do you want to Exit ?<br/>"+ 
        ,callMeBack1,"Please Answer"); 
1

en mi expe ¡esta es la mejor y más fácil forma de tener una confirmación!

<a href="#" onclick="return myconfirm()">Confirm</a> 
<script> 
function myconfirm() 
{ 
    if(confirm('Are You Sure ...')) 
     return true; 
    return false; 
} 
</script> 
+1

una forma aún más fácil sería usar el valor de retorno de la función de confirmación: 'onclick =" return confirm ('Are you sure?') "' – Andrew

Cuestiones relacionadas