How to build a jQuery dialog for confirmation (yes/no) that can work anywhere in an app?

24,297

Solution 1

Example using JQuery UI dialog -

Demo - http://jsfiddle.net/CdwB9/3/

function yesnodialog(button1, button2, element){
  var btns = {};
  btns[button1] = function(){ 
      element.parents('li').hide();
      $(this).dialog("close");
  };
  btns[button2] = function(){ 
      // Do nothing
      $(this).dialog("close");
  };
  $("<div></div>").dialog({
    autoOpen: true,
    title: 'Condition',
    modal:true,
    buttons:btns
  });
}
$('.delete').click(function(){
    yesnodialog('Yes', 'No', $(this));
})

With live -

Demo - http://jsfiddle.net/CdwB9/4/

$('.delete').live('click', function(){
    yesnodialog('Yes', 'No', $(this));
})

Solution 2

I've done something similar. On a very high level, you have to stop the propagation of the click, display the dialog, then trigger the click again based on the response.

var confirmed = false;

$('span.delete').click(function(e) {
    if (!confirmed) {
        var that = $(this);

        $( "#dialog-confirm" ).dialog({
            buttons: {
                "Delete": function() {
                    confirmed = true;
                    that.trigger('click');
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog( "close" );
                }
            }
        });

        e.stopPropagation();
    } else {
        confirmed = false;
    }
});
Share:
24,297
AnApprentice
Author by

AnApprentice

working on Matter, a new way to gather professional feedback.

Updated on October 28, 2020

Comments

  • AnApprentice
    AnApprentice over 3 years

    I have the following:

    <ol id="listItems>
        <li id="listItem-1">
            <span class="title">Item 1</span>
            <span class="delete">delete</span>
        </li>
        <li id="listItem-2">
            <span class="title">Item 2</span>
            <span class="delete">delete</span>
        </li>
        <li id="listItem-3">
            <span class="title">Item 3</span>
            <span class="delete">delete</span>
        </li>
        <li id="listItem-4">
            <span class="title">Item 4</span>
            <span class="delete">delete</span>
        </li>
    </ol>
    

    What I want to do here is anytime .delete is clicked, I want to show a jQuery ui-dialog for confirmation, Yes or No.... If the user says yes then continue with the delete click where it will be deleted as is today.

    How can I build a jQuery UI Dialog that is static and would work for any number of list items? Better yet would work for anything in my app so it's not just list specific.

    Ideas? Thanks