I am using jQuery 1.9+
I tried to popup a Jquery dialog modal to allow users to confirm before switching tabs. I tried following codes:
$('#tabs').tabs({
beforeActivate: function(event, ui) {
$('<div> Confirm Switching Tab </div>').dialog({
modal: true,
title: "Confirm Action",
buttons: {
Yes: function(){
$(this).dialog('close');
return true;
},
No: function(){
$(this).dialog('close');
return false;
}
}
});
}
})
The code above did popup the confirm dialog, however it still open the tab because the beforeActivate event in fact returns before users click the dialog buttons to return true/false.
Then I come up with the following codes.
$('#tabs').tabs({
beforeActivate: function(event, ui) {
$('<div> Confirm Switching Tab </div>').dialog({
modal: true,
title: "Confirm Action",
buttons: {
Yes: function(){
$(this).dialog('close');
$( "#tabs" ).tabs( "option", "active", ui.newTab.index());
},
No: function(){
$(this).dialog('close');
}
}
});
return false;
}
})
The code above wont open the tab because I put "return false" at the end of the beforeActivate option. After beforeActivate is returned, dialog popups, if users click the Yes button on the dialog, then it will trigger switching tabs event again. However, the dialog will popup again. This is kind of endless.
My question is that how I can modify the codes above to do that. Or is there any better way to do it?
Thanks in advance.
The major issue is that, beforeActivate is triggered even when you're switching the tab programatically like
Causing an infinite loop as long as you keeps pressing yes - the dialog will never close (new dialogs will be opened keep on opened one after another).
One possible work around I can think of is to have a static dialog, and save a boolean flag using using data() to indicate how the event was triggered.
One option is to store a variable that determines whether or not the user answered "Yes". Since
ui.newTab
is a jQuery object, you can store it in it's.data
Fiddle Here: http://jsfiddle.net/ktc1uuca/