Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use jquery UI dialog as javascript confirm?

I read lots of questions about this, but every solution uses the same workaround, submiting the form inside the jquery dialog, something like this:

 $("#dialog").dialog({
  buttons : {
    "Confirm" : function() {
      window.location.href = targetUrl;
    },
    "Cancel" : function() {
      $(this).dialog("close");
    }
  }

Isn't there an easier way, more like javascript confirm?

<input type="submit" onclick="return confirm('are you sure?');" />

Why something like return true, return false doesn't work?

like image 750
Alex Angelico Avatar asked Feb 27 '26 19:02

Alex Angelico


2 Answers

Here's what you can do, you change your input type from 'submit' to 'button', then, you can have your script like this:

$(document).ready(function(){ 
  $("#dialog").dialog({
    autoOpen: false, 
    buttons : {
        "Confirm" : function() {
          $('#form1').submit();
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });
  $('#submitButton').click(function(){
      $("#dialog").dialog('open');
  });
});

This way your form will only be submitted when the used confirms the dialog.

The reason it doesn't matter if you return false or true in your case is that the dialog is just shown but code from the submit event keeps on executing unless you return false just after showing the dialog.

like image 63
Arturo Molina Avatar answered Mar 01 '26 08:03

Arturo Molina


I wrote the following code to use JQuery's UI Dialog as a modal confirmation. By submitting the form via the event target there is not a recursive call to the submit event handler.

$(function () {
    $('form[action*="/Delete"]').submit(function (e) {
        e.preventDefault();

        $("<div>Are you sure you want to delete this?</div>").dialog({
            resizable: false,
            height: 140,
            modal: true,
            buttons: {
                Ok: function () {
                    e.target.submit();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    });
}); 
like image 41
William Avatar answered Mar 01 '26 10:03

William



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!