Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Calling jQuery Dialog twice

I have 2 functions: myFunc1 and myFunc2. When myFunc1 is called, a jQuery confirmation Dialog appears. When the user clicks yes, myFunc2 is called, which should show another dialog.
But, despite successfully calling myFunc2, the second dialog never appears.

Here is a fiddle.

function myFunc1() {
  dialog().then(function(data) {
    if (data == "yes") {
      console.log("clicked yes: show another dialog")
      myFunc2();
    } else {
      console.log("clicked no")
    }
  });
}

function myFunc2() {
  dialog();
  console.log("myFunc2 is called")
}

function dialog(title) {
  var def = $.Deferred();
  $("#dialog").dialog({
    modal: true,
    buttons: {
      "Yes": function() {
        def.resolve("yes");
        $(this).dialog("close");
      },
      "No": function() {
        def.resolve("no");
        $(this).dialog("close");
      }
    }
  });
  return def.promise();
}

$("button").on("click", myFunc1);

Upvotes: 2

Views: 445

Answers (2)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

You're using the same div to create all your dialogs, if you need to have more than one dialog open at once that will be an issue.

// Get a random unique number to use as the dialog id
var guid = Math.floor(Math.random() * 9999999999999) + 1;
// Clone the dialog div and give it a new name
$("#dialog").clone()[0].id = guid;
// Create the dialog with the new unique div
$("#"+guid).dialog({...});

Also,

// Make sure you remove the div after you close it
$(this).dialog("close").remove();

Upvotes: 0

empiric
empiric

Reputation: 7878

You are resolving the Deffered-Object before you are actually closing the first dialog. So when the then()-callback is hit, the dialog is still open, therefore no new one is created.

Just swap the functions and it should be working.

"Yes": function() {
    $(this).dialog("close");
    def.resolve("yes");           
},

Example

When the Deferred is resolved, any doneCallbacks added by deferred.then() or deferred.done() are called. Callbacks are executed in the order they were added

.resolve()

Upvotes: 4

Related Questions