jQuery UI modal dialog closes on clicking itself
I have a modal popup in my page which closes itself when I click on any control in that dialog, below is the code:
function overlayclickclose() {
if (closedialog) {
jQuery('#mydialog').dialog('close');
}
}
closedialog = 1;
jQuery('#mydialog').dialog({
bgiframe: true,
autoOpen: false,
modal: true,
width: 900,
height: 400,
resizable: false,
open: function() {
closedialog = 1;
jQuery(document).bind('click', overlaycl开发者_开发百科ickclose);
},
focus: function() {
closedialog = 1;
},
close: function() {
jQuery(document).unbind('click');
}
});
When I click on that modal dialog anywhere, it closes so I can not operate on it. How can I fix it?
Note that my div is in an update panel and puts a user control of ASP.NET Inside.
If you want to know why the dialog is closing as soon as you click anywhere in your dialog. You have added a .click()
event listener to the whole document, every time a click occurs, it will run your callback function overlayclickclose()
.
That is checking to see if you want to close the dialog:
if (closedialog)
As closedialog
is always 1
which as a boolean is true any click anywhere will close the dialog. Your function will basically say if (true)
do something, so will always 'do something'.
If you change your focus event to:
closedialog = 0;
Close dialog is now 0
which as a boolean is flase so the dialog wont close.
See it working here
See it not working as you have it here
After a quick search, it looks like the code you are using is something very similar to this tutorial - see the use of 1
and 0
for the closedialog
variable.
There is another way you can do this, its probably easier to follow in code. See the question here. You can change your code to something like this:
$('#mydialog').dialog({
bgiframe: true,
autoOpen: true,
modal: true,
width: 300,
height: 200,
resizable: false
});
$('.ui-widget-overlay').live('click', function() {
$('#mydialog').dialog('close');
});
See it working here
If the question is "why does this dialog close when elements inside of it are clicked?", then the answer is that the click events from the sub-elements are propagating to the parent element. See event.stopPropagation() for details of how to stop this happening. I hope this helps.
精彩评论