I have a jQuery dialog that need to open when i click the class .currentDay, this works but only on the second click. I'm thinking that i am initializing the modal on the first click and then opening it on the second.
I have tried different stuff to make it init and open, but i just cant seem to make it work. Hopefully someone on here can give me a hand.
this is the JavaScript that i currently have.
$('.currentDay').click(function () {
var id = event.target.id;
var url = '/Home/CalenderPartial/' + id;
var dialog = $('<div style="display:none"></div>').appendTo('body');
dialog.load(url, {},
function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
autoOpen: true,
closeText: "",
width: $(window).width() - 300,
height: $(window).height() - 100,
close: function (event, ui) {
dialog.remove();
}
});
});
return false;
});
It also throws an error: Uncaught TypeError: dialog.dialog is not a function, but it is still working.
Did you try to prevent default anchor behavior?
$('.currentDay').click(function ( e ) {
e.preventDefault();
alert('test');
});
All credit to earlyer post on github: Source
Its working fine for me... please check working example
$('.currentDay').click(function () {
var id = event.target.id;
var url = '/Home/CalenderPartial/' + id;
var dialog = $('<div style="display:none"></div>').appendTo('body');
dialog.load(url, {},
function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
autoOpen: true,
closeText: "",
width: $(window).width() - 300,
height: $(window).height() - 100,
close: function (event, ui) {
dialog.remove();
}
});
});
return false;
});
#import "//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css";
#import "/resources/demos/style.css";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<button class="currentDay">BTN 1</button>
<button class="currentDay">BTN 2</button>
<button class="currentDay">BTN 3</button>
I've added a jquery UI dialog to an mvc page. After the dialog is opened I need to catch the bool values if the dialog is dismissed or confirmed.
So far I have tried to add a call back as mentioned in another answer, but I'm not sure how to pass that value back to the $('#escalation').on('click', '.delete', function (evt) so that I may perform a redirect if true.
Question:
How can I pass back a bool value to calling function from Jquery UI modal dialog?
Pseudo code:
This is my intended flow of execution for the below fuctions:
1.Call dialog open on a button click. - (working)
2.Pass back true or false depending on if the user selected 'ok' or 'cancel' in the modal dialog.
3.Close the dialog if the returned result to the button click event is false. Otherwise call window.location.href = RedirectTo; code.
Code:
Dialog markup -
<div id="dialog-confirm" title="Delete Selected Record?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This record will be permanently deleted.</p> <p>Are you sure?</p>
</div>
Jquery scripts -
<script>
var baseUri = '#Url.Content("~")';
$(document).ready(function () {
$('#escalation').DataTable({
"order": [[6, "desc"]]
});
$('#escalation').on('click', '.delete', function (evt) {
var cell = $(evt.target).closest("tr").children().first();
var EscalationID = cell.text();
var RedirectTo = baseUri + "/EscalationHistory/DeleteEscalation?EscalationID=" + EscalationID;
////open dialog
evt.preventDefault();
$("#dialog-confirm").dialog("open");
//Need to call this code if the dialog result callback equals true
window.location.href = RedirectTo;
//Otherwise do nothing..close dialog
});
//Dialog opened here, not sure how to pass back the boolean values
//to the delete click function above
$("#dialog-confirm").dialog({
autoOpen: false,
modal: true,
buttons: {
"Confirm": function () {
callback(true);
},
"Cancel": function () {
$(this).dialog("close");
callback(false);
}
}
});
});
</script>
Just write your target code inside button click handler or set a flag and use $(".selector").on("dialogclose", function(event, ui) {}); event handler to check the flag state.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/jquery-ui.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script>
$(function() {
var baseUri = "http://localost";
$("#dialog-confirm").dialog({
autoOpen: false,
modal: true,
resizable: false,
width: 450,
open: function() {
$(this).data("state", "");
},
buttons: {
"OK": function() {
$(this).data("state", "confirmed").dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
$(".btn").click(function() {
var escalationId = $(this).data("escalation-id");
var redirectTo = baseUri + "/EscalationHistory/DeleteEscalation?EscalationID=" + escalationId;
// Use "bind" instead "on" if jQuery < 1.7
$("#dialog-confirm").dialog("open").on("dialogclose", function(event, ui) {
if ($(this).data("state") == "confirmed") {
location.replace(redirectTo);
}
});
});
});
</script>
</head>
<body>
<button class="btn" data-escalation-id="123">Delete 123</button>
<button class="btn" data-escalation-id="124">Delete 124</button>
<div id="dialog-confirm" style="display:none">Are you sure?</div>
</body>
</html>
But, IMO, logically better to write the code directly in button click handler.
I am using jquery UI dialog to show comments or other text depending upon what is clicked.
Here is my JSfiddle link Dialog Demo
I have used the code
$('.showComments').each(function () {
var panel = $(this).parent().siblings('.divCommentDetail');
$(this).click(function () {
panel.dialog('open');
});
});
$('.showContractChanges').each(function () {
var panel = $(this).parent().siblings('.divContractChangeDetail');
$(this).click(function () {
panel.dialog('open');
});
});
$(".divCommentDetail, .divContractChangeDetail").dialog({
autoOpen: false,
modal: true,
open: function () {
$(this).parent().siblings('.ui-dialog-titlebar').addClass('ui-state-error');
},
show: {
effect: 'blind',
duration: 1000
},
hide: {
effect: 'explode',
duration: 1000
}
});
and the content is added dynamically on page load. I am trying to use $(document).on('each', '.showComments', function(e) {}); so that it can work with dynamically loaded content, but it doesn't work at all. here is my modified code.
$(document).on('each', '.showComments', function () {
var panel = $(this).parent().siblings('.divCommentDetail');
$(this).click(function () {
panel.dialog('open');
});
});
but this doesn't work at all. Am i doing something wrong.
Thanks for the help.
If the .divContentDetail is added dynamically after page load, it's not the loop you need to change, but the event that you are registering:
$(document).on('click', '.showComments', function () {
var panel = $(this).parent().siblings('.divCommentDetail');
panel.dialog('open');
});
.on bind event that work on dynamicly added elements. But 'each' is not an event, it's a method.
You should use on like that :
$(document).on('click', '.showComments', function () {
var panel = $(this).parent().siblings('.divCommentDetail');
panel.dialog('open');
});
I have a page that call from ajax a form with a specific target. this form has a delete entry and for that a warning with a jQuery dialog is used. everything works great.
BUT :
After doing the change or even not doing it, when I open another form (different form by ajax call) and I call the same code below described. When It is submit the dialog the #var_blabla as a value of 1 (the value of the first dialog opened/loaded) and for that moment should be '2'.
I try to figure it out.. So my problem I guess is not for the dialog it self, since I try to load a second page without the constructor and the dialog didn't open (what should be expected).
The problem is on the button 'Submit Delete' that has an event function and it stays active over another that is created.
The site have a lot of forms and many dialogs for each form, is there a wait to unbind, or destroy completely the dialog and the buttons? Ideas please?
Thanks
simplified 1st dialog call code:
$("#dialog-confirm-elimina").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Submit Delete': function() { $('#var_blabla').val('1');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
simplified 2nd dialog call code:
$("#dialog-confirm-elimina").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Submit Delete': function() { $('#var_blabla').val('2');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
UPDATE:
<script type="text/javascript">
submited=false;
var toggleOpened = true;
$("#admin_retractil_1").click(function () {
if(!toggleOpened){
$('#admin_retractil_1').toggleClass('toggleGESBHeadown');
toggleOpened=true;
}
else{
$('#admin_retractil_1').toggleClass('toggleGESBHeadown');
toggleOpened=false;
}
var objecto = $(this).attr("id");
$('#' + objecto+"_div").slideToggle("slow");
});
var toggleOpened2 = false;
$("#admin_retractil_2").click(function () {
if(!toggleOpened2){
$('#admin_retractil_2').toggleClass('toggleGESAHeadown');
toggleOpened2=true;
}
else{
$('#admin_retractil_2').toggleClass('toggleGESAHeadown');
toggleOpened2=false;
}
var objecto = $(this).attr("id");
$('#' + objecto+"_div").slideToggle("slow");
});
$(document).ready(function() {
//$( "button").button();
var locked = true;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-locked" }});
$( "#EditDataForm" ).click(function() {
if(locked){
locked = false;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-unlocked" }});
$('#edit_data_admin').slideToggle("slow");
$('#view_data_admin').slideToggle("slow");
}else{
locked = true;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-locked" }});
$('#edit_data_admin').slideToggle("slow");
$('#view_data_admin').slideToggle("slow");
}
return false; });
$( "#DelDataForm").button({ icons: { primary: "ui-icon-scissors" }});
$( "#DelDataForm" ).click(function() {
$('#dialog-confirm-del').dialog('open');
return false; });
/*abre popup de alerta de eliminar */
arrayRemove.push("dialog-confirm-del");
$("#dialog-confirm-del").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Remove Stuff': function() {
$('#sel_action_form').val('TypoDesClients_DelDef');
$('#name').val('_____');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancelar: function() {
$(this).dialog('close');
}
}
});
$( "#AcceptChanges").button({ icons: { primary: "ui-icon-check" }});
$("#form_submeter").validator({
position: 'center right',
offset: [0, 0],
message: '<div><em /></div>'
}).bind("onSuccess", function(e, els) {
var numSucceeded = els.length,
numExpected = $(this).data('validator').getInputs().length;
if (numSucceeded === numExpected) {
if(!submited){submited=true;
SubmitFormSV('form_submit', 'action/action_a.php');
return false;
}else return false;
}
});
$( "#radio" ).buttonset();
$("#1_radio").click(function () {
$("#tr_1").show();
});
$("#2_radio").click(function () {
$("#tr_1").hide();
});
});
local lib:
function SubmitFormSV(formul, address)
{
DoChecks();
$("#loading").show("slow");
$.post(baseURL + address, $('#' + formul).serialize(), function(html){
$('#content').slideUp("slow", function () {
AjaxChargePage(html, true);
});
});
$("#loading").hide("slow");
return false;
}
next the next chuck of javascript is similar to this one.
and with this work because destroy didn't:
DoChecks() As:
$.each(arrayRemove, function() {
var element = arrayRemove.pop();
$('#'+element).remove();
});
When you're done with dialog 1 try...
$("#dialog-confirm-elimina").dialog("destroy");
or in your Cancel function...
$(this).dialog("destroy");
The .dialog command creates a new dialog on the element selected. You're doing this twice, and thus having problems. Once the dialog is created it can be reused using open and close methods or destroyed as I've shown above and then recreated.
Ok, then finally I got a solution that make everything works. Instead of using the
$("#dialog-confirm-elimina").dialog("destroy");
I use:
$("#dialog-confirm-elimina").remove();
I still don't know the reason but clearly don't have the problem anymore.
Thanks for the answer though.
PS: If anyone know how could this append I appreciate to illuminate me about it.Thanks
I have a jQuery UI Dialog that gets displayed when specific elements are clicked. I would like to close the dialog if a click occurs anywhere other than on those triggering elements or the dialog itself.
Here's the code for opening the dialog:
$(document).ready(function() {
var $field_hint = $('<div></div>')
.dialog({
autoOpen: false,
minHeight: 50,
resizable: false,
width: 375
});
$('.hint').click(function() {
var $hint = $(this);
$field_hint.html($hint.html());
$field_hint.dialog('option', 'position', [162, $hint.offset().top + 25]);
$field_hint.dialog('option', 'title', $hint.siblings('label').html());
$field_hint.dialog('open');
});
/*$(document).click(function() {
$field_hint.dialog('close');
});*/
});
If I uncomment the last part, the dialog never opens. I assume it's because the same click that opens the dialog is closing it again.
Final Working Code
Note: This is using the jQuery outside events plugin
$(document).ready(function() {
// dialog element to .hint
var $field_hint = $('<div></div>')
.dialog({
autoOpen: false,
minHeight: 0,
resizable: false,
width: 376
})
.bind('clickoutside', function(e) {
$target = $(e.target);
if (!$target.filter('.hint').length
&& !$target.filter('.hintclickicon').length) {
$field_hint.dialog('close');
}
});
// attach dialog element to .hint elements
$('.hint').click(function() {
var $hint = $(this);
$field_hint.html('<div style="max-height: 300px;">' + $hint.html() + '</div>');
$field_hint.dialog('option', 'position', [$hint.offset().left - 384, $hint.offset().top + 24 - $(document).scrollTop()]);
$field_hint.dialog('option', 'title', $hint.siblings('label').html());
$field_hint.dialog('open');
});
// trigger .hint dialog with an anchor tag referencing the form element
$('.hintclickicon').click(function(e) {
e.preventDefault();
$($(this).get(0).hash + ' .hint').trigger('click');
});
});
Sorry to drag this up after so long but I used the below. Any disadvantages? See the open function...
$("#popup").dialog(
{
height: 670,
width: 680,
modal: true,
autoOpen: false,
close: function(event, ui) { $('#wrap').show(); },
open: function(event, ui)
{
$('.ui-widget-overlay').bind('click', function()
{
$("#popup").dialog('close');
});
}
});
Forget using another plugin:
Here are 3 methods to close a jquery UI dialog when clicking outside popin:
If the dialog is modal/has background overlay: http://jsfiddle.net/jasonday/6FGqN/
jQuery(document).ready(function() {
jQuery("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 100,
modal: true,
open: function(){
jQuery('.ui-widget-overlay').bind('click',function(){
jQuery('#dialog').dialog('close');
})
}
});
});
If dialog is non-modal Method 1: method 1: http://jsfiddle.net/jasonday/xpkFf/
// Close Pop-in If the user clicks anywhere else on the page
jQuery('body')
.bind(
'click',
function(e){
if(
jQuery('#dialog').dialog('isOpen')
&& !jQuery(e.target).is('.ui-dialog, a')
&& !jQuery(e.target).closest('.ui-dialog').length
){
jQuery('#dialog').dialog('close');
}
}
);
Non-Modal dialog Method 2: http://jsfiddle.net/jasonday/eccKr/
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
minHeight: 100,
width: 342,
draggable: true,
resizable: false,
modal: false,
closeText: 'Close',
open: function() {
closedialog = 1;
$(document).bind('click', overlayclickclose);
},
focus: function() {
closedialog = 0;
},
close: function() {
$(document).unbind('click');
}
});
$('#linkID').click(function() {
$('#dialog').dialog('open');
closedialog = 0;
});
var closedialog;
function overlayclickclose() {
if (closedialog) {
$('#dialog').dialog('close');
}
//set to one because click on dialog box sets to zero
closedialog = 1;
}
});
Check out the jQuery Outside Events plugin
Lets you do:
$field_hint.bind('clickoutside',function(){
$field_hint.dialog('close');
});
Just add this global script, which closes all the modal dialogs just clicking outsite them.
$(document).ready(function()
{
$(document.body).on("click", ".ui-widget-overlay", function()
{
$.each($(".ui-dialog"), function()
{
var $dialog;
$dialog = $(this).children(".ui-dialog-content");
if($dialog.dialog("option", "modal"))
{
$dialog.dialog("close");
}
});
});;
});
$(".ui-widget-overlay").click (function () {
$("#dialog-id").dialog( "close" );
});
Fiddle showing the above code in action.
I had to do two parts. First the outside click-handler:
$(document).on('click', function(e){
if ($(".ui-dialog").length) {
if (!$(e.target).parents().filter('.ui-dialog').length) {
$('.ui-dialog-content').dialog('close');
}
}
});
This calls dialog('close') on the generic ui-dialog-content class, and so will close all dialogs if the click didn't originate in one. It will work with modal dialogs too, since the overlay is not part of the .ui-dialog box.
The problem is:
Most dialogs are created because of clicks outside of a dialog
This handler runs after those clicks have created a dialog and bubbled up to the document, so it immediately closes them.
To fix this, I had to add stopPropagation to those click handlers:
moreLink.on('click', function (e) {
listBox.dialog();
e.stopPropagation(); //Don't trigger the outside click handler
});
This question is a bit old, but in case someone wants to close a dialog that is NOT modal when user clicks somewhere, you can use this that I took from the JQuery UI Multiselect plugin. The main advantage is that the click is not "lost" (if user wants to click on a link or a button, the action is done).
$myselector.dialog({
title: "Dialog that closes when user clicks outside",
modal:false,
close: function(){
$(document).off('mousedown.mydialog');
},
open: function(event, ui) {
var $dialog = $(this).dialog('widget');
$(document).on('mousedown.mydialog', function(e) {
// Close when user clicks elsewhere
if($dialog.dialog('isOpen') && !$.contains($myselector.dialog('widget')[0], e.target)){
$myselector.dialog('close');
}
});
}
});
You can do this without using any additional plug-in
var $dialog= $(document.createElement("div")).appendTo(document.body);
var dialogOverlay;
$dialog.dialog({
title: "Your title",
modal: true,
resizable: true,
draggable: false,
autoOpen: false,
width: "auto",
show: "fade",
hide: "fade",
open:function(){
$dialog.dialog('widget').animate({
width: "+=300",
left: "-=150"
});
//get the last overlay in the dom
$dialogOverlay = $(".ui-widget-overlay").last();
//remove any event handler bound to it.
$dialogOverlay.unbind();
$dialogOverlay.click(function(){
//close the dialog whenever the overlay is clicked.
$dialog.dialog("close");
});
}
});
Here $dialog is the dialog.
What we are basically doing is to get the last overlay widget whenever this dialog is opened and binding a click handler to that overlay to close $dialog as anytime the overlay is clicked.
no need for the outside events plugin...
just add an event handler to the .ui-widget-overlay div:
jQuery(document).on('click', 'body > .ui-widget-overlay', function(){
jQuery("#ui-dialog-selector-goes-here").dialog("close");
return false;
});
just make sure that whatever selector you used for the jQuery ui dialog, is also called to close it.. i.e. #ui-dialog-selector-goes-here
This doesn't use jQuery UI, but does use jQuery, and may be useful for those who aren't using jQuery UI for whatever reason. Do it like so:
function showDialog(){
$('#dialog').show();
$('*').on('click',function(e){
$('#zoomer').hide();
});
}
$(document).ready(function(){
showDialog();
});
So, once I've shown a dialog, I add a click handler that only looks for the first click on anything.
Now, it would be nicer if I could get it to ignore clicks on anything on #dialog and its contents, but when I tried switching $('*') with $(':not("#dialog,#dialog *")'), it still detected #dialog clicks.
Anyway, I was using this purely for a photo lightbox, so it worked okay for that purpose.
The given example(s) use one dialog with id '#dialog', i needed a solution that close any dialog:
$.extend($.ui.dialog.prototype.options, {
modal: true,
open: function(object) {
jQuery('.ui-widget-overlay').bind('click', function() {
var id = jQuery(object.target).attr('id');
jQuery('#'+id).dialog('close');
})
}
});
Thanks to my colleague Youri Arkesteijn for the suggestion of using prototype.
This is the only method that worked for me for my NON-MODAL dialog
$(document).mousedown(function(e) {
var clicked = $(e.target); // get the element clicked
if (clicked.is('#dlg') || clicked.parents().is('#dlg') || clicked.is('.ui-dialog-titlebar')) {
return; // click happened within the dialog, do nothing here
} else { // click was outside the dialog, so close it
$('#dlg').dialog("close");
}
});
All credit goes to Axle
Click outside non-modal dialog to close
For those you are interested I've created a generic plugin that enables to close a dialog when clicking outside of it whether it a modal or non-modal dialog. It supports one or multiple dialogs on the same page.
More information here: http://www.coheractio.com/blog/closing-jquery-ui-dialog-widget-when-clicking-outside
Laurent
I use this solution based in one posted here:
var g_divOpenDialog = null;
function _openDlg(l_d) {
// http://stackoverflow.com/questions/2554779/jquery-ui-close-dialog-when-clicked-outside
jQuery('body').bind(
'click',
function(e){
if(
g_divOpenDialog!=null
&& !jQuery(e.target).is('.ui-dialog, a')
&& !jQuery(e.target).closest('.ui-dialog').length
){
_closeDlg();
}
}
);
setTimeout(function() {
g_divOpenDialog = l_d;
g_divOpenDialog.dialog();
}, 500);
}
function _closeDlg() {
jQuery('body').unbind('click');
g_divOpenDialog.dialog('close');
g_divOpenDialog.dialog('destroy');
g_divOpenDialog = null;
}
I had same problem while making preview modal on one page. After a lot of googling I found this very useful solution. With event and target it is checking where click happened and depending on it triggers the action or does nothing.
Code Snippet Library site
$('#modal-background').mousedown(function(e) {
var clicked = $(e.target);
if (clicked.is('#modal-content') || clicked.parents().is('#modal-content'))
return;
} else {
$('#modal-background').hide();
}
});
İt's simple actually you don't need any plugins, just jquery or you can do it with simple javascript.
$('#dialog').on('click', function(e){
e.stopPropagation();
});
$(document.body).on('click', function(e){
master.hide();
});
I don't think finding dialog stuff using $('.any-selector') from the whole DOM is so bright.
Try
$('<div />').dialog({
open: function(event, ui){
var ins = $(this).dialog('instance');
var overlay = ins.overlay;
overlay.off('click').on('click', {$dialog: $(this)}, function(event){
event.data.$dialog.dialog('close');
});
}
});
You're really getting the overlay from the dialog instance it belongs to, things will never go wrong this way.
With the following code, you can simulate a click on the 'close' button of the dialog (change the string 'MY_DIALOG' for the name of your own dialog)
$("div[aria-labelledby='ui-dialog-title-MY_DIALOG'] div.ui-helper-clearfix a.ui-dialog-titlebar-close")[0].click();
Smart Code:
I am using following code so that every thing remains clear and readable.
out side body will close the dialog box.
$(document).ready(function () {
$('body').on('click', '.ui-widget-overlay', closeDialogBox);
});
function closeDialogBox() {
$('#dialog-message').dialog('close');
}
I ended up using this code which should work on any open dialogs on the page, ignores clicks on tooltips, and cleans up the resources of the dialog being closed as well.
$(document).mousedown(function(e) {
var clicked = $(e.target); // get the element clicked
if (clicked.is('.ui-dialog-content, .ui-dialog-titlebar, .ui-tooltip') || clicked.parents().is('.ui-dialog-content, .ui-dialog-titlebar, .ui-tooltip')) {
return; // click happened within the dialog, do nothing here
} else { // click was outside the dialog, so close it
$('.ui-dialog-content').dialog("close");
$('.ui-dialog-content').dialog("destroy");
$('.ui-dialog-content').detach();
}
});
I just ran across the need to close .dialog(s) with an out of element click. I have a page with a lot of info dialogs, so I needed something to handle them all. This is how I handled it:
$(document).ready(function () {
$(window).click(function (e) {
$(".dialogGroup").each(function () {
$(this).dialog('close');
})
});
$("#lostEffClick").click(function () {
event.stopPropagation();
$("#lostEffDialog").dialog("open");
};
});