jQuery UI: model dialog 'close' - javascript

I have 2 Razor views where one is loading the other in a jQuery UI dialog. In the view that get loaded in the dialog; I am opening another jQuery UI dialog to display a message.
The objective is to close both the dialogs when message dialog Cancel button is clicked.
Razor code is as follows:
Main View
<button id="openModel" onclick="openModel()">
<div id="mainDialog" />
<script type="text/javascript">
function openModel() {
$('#mainDialog').dialog({
open: function () {
// loading "the secondary view in the model dialog"
// url: controller-action url to load the second view
$(this).load('url');
}
});
}
</script>
Dialog View
<button id="messageOpener">Verify</button>
<div id="messageDialog" />
<script type="text/javascript">
$(document).ready(function () {
$("#messageOpener").click(function () {
$("#messageDialog").dialog("open");
return false;
});
$("#messageDialog").dialog({
buttons: {
Retry: function () {
$(this).dialog("close");
},
Cancel: function () {
// **** ?? must close both dialogs. ****
}
},
autoOpen: false,
});
});
</script>
I have tried following approaches to close the dialogs:
Approach 01:
$(".ui-dialog-content").dialog("close");
Approach 02:
$(this).dialog("close");
$("#mainDialog").dialog("close");
Approach 03:
$(".ui-dialog:visible").find(".dialog").dialog("close");
But all above does not close the dialogs as expected instead produces the following JS error:
Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
v.extend.error
(anonymous function)
v.extend.each
v.fn.v.each
e.fn.(anonymous function)
$.dialog.buttons.Cancel
r.click
v.event.dispatch
o.handle.u

Re-writing the code in the following way solve the problem..
1. Main View
<button id="openModel" onclick="openModel()">
<div id="mainDialog" />
<script type="text/javascript">
var $modelDialog = $('#mainDialog').dialog({
autoOpen: false,
open: function () {
// loading "the secondary view in the model dialog"
// url: controller-action url to load the second view
$(this).load('url');
}
});
function openModel() {
$modelDialog.dialog('open');
}
function closeModel() {
$modelDialog.dialog('close');
}
</script>
2. Dialog View
<button id="messageOpener">Verify</button>
<div id="messageDialog" />
<script type="text/javascript">
var $messageDialog;
$(document).ready(function () {
$("#messageOpener").click(function () {
$messageDialog.dialog("open");
return false;
});
$messageDialog = $("#messageDialog").dialog({
buttons: {
Retry: function () {
$messageDialog.dialog("close");
},
Cancel: function () {
// [!!]
$messageDialog.dialog("destroy");
closeModel();
}
},
autoOpen: false,
});
});
</script>

Approach 2 looks fine , but you get that error cause the mainDialog modal is not opened when you try to close the message dialog. Also, function openModel is not getting called anywhere.

Related

Dialog is not a function (how to display custom dialog)

I want to display on my web application a custom dialog. So I'm building this code:
<script type="text/javascript">
var mappaRisposte = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.mappaRisposte));
ConfirmDialog('Are you sure');
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '?</h6></div>')
.dialog({
modal: true,
title: 'Delete message',
zIndex: 10000,
autoOpen: true,
width: 'auto',
resizable: false,
buttons: {
Yes: function () {
// $(obj).removeAttr('onclick');
// $(obj).parents('.Parent').remove();
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
},
No: function () {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
}
</script>
These are the external library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<!---->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
So if I try to execute this page, I can see this:
But if I try to call ConfirmDialog function from another js function in this mode:
function endFirstPartSummary() {
ConfirmDialog('Are you sure');
var parolaChiave = document.getElementById("tParolaChiave").value;
//alert(parolaChiave);
$.ajax({
url: '/Questionario/endFirstPartSummary',
data: { "json": JSON.stringify(parolaChiave)},
type: "GET",
success: function (data) {
//TODO: Add whatever if you want to pass a notification back
location.href='#Url.Action("PageRingraziamento", "PageRingraziamento")'
},
error: function (error) {
//TODO: Add some code here for error handling or notifications
//alert("Il nome di fantasia indicato è già stato utilizzato, inventane un altro");
document.getElementById("tParolaChiave").value = "";
}
});
}
I have this error from console:
TypeError: $(...).appendTo(...).html(...).dialog is not a function
As far as i understand, you try using the very same dialog object twice, but on the second attempt you are getting an error.
Try saving the instance global (not inside an function), like:
const myDialog = $("#dialog").dialog('open');
and reuse it like:
myDialog.dialog("close"); // or maybe: myDialog.close();
At the moment you are using "$(this).dialog("close");" in the context of an function. So "this" is the function, not the dialog.

Client Side validations not working in jQuery UI Dialog

I searched and found lot of answers, still i am not able to validate fields in my jQuery UI Dialog. Please suggest appropriate ways for the same.
Parent View:
<div id="dialog" title="Add New">
<p>Div content</p>
</div>
<script type="text/javascript">$(function () {
$('#btnAddNew').click(function () {
$('#dialog').dialog
({
autoOpen: true,
modal: true,
open: function (event, ui) {
$(this).load("#Url.Action("AddNewFormPart1")"); //Rendering Partial View
}
});
});
});
<script/>
Partial View:
#using (Html.BeginForm("SubmitFormPart1", "Home", FormMethod.Post, new { #id = "formPart1" }))
{
#Html.ValidationSummary()
<div>......
<input type="submit" value="Submit" id="btnSubmitFormPart1"/>
</div>
}
Validator should parse partial page after loading partial page. if you are using Unobtrusive Validation:
$(this).load('#Url.Action("AddNewFormPart1")', function(response, status, xhr){
var form = $("#AddNewFormPart1");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
})
It is because your content are loaded after the plugin call!
You need to call the validation plugin after loading the partial view as follows(Notice the .done(function*({}) helper).
<script type="text/javascript">$(function () {
$('#btnAddNew').click(function () {
alert('Add New clicked!');
$('#dialog').dialog
({
autoOpen: true,
modal: true,
open: function (event, ui) {
$(this).load("#Url.Action("AddNewFormPart1")").done(function(){
//CALL YOUR VALIDATION PLUGIN HERE
//$('#formPart1').validate({...});
}); //Rendering Partial View
}
});
});
});

Error when clicking buttons in jquery dialog

I'm able to get the dialog to appear when I click "Reject Request", but the dialog won't close and I see an error in the console when I click Cancel or OK. "Uncaught TypeError: Cannot read property 'apply' of undefined"
HTML:
<button id="btn-reject" class="btn btn-danger" type="submit" style="float: right;">Reject Request</button>
<div id='reject-dialog' title='Confirmation Required'>Reject Request?</div>
JQuery:
<script type="text/javascript">
$(document).ready(function () {
$("#reject-dialog").dialog({
autoOpen: false,
modal: true,
buttons: {
"Confirm": {
text: "OK",
id: "confirm-reject"
},
"Cancel": {
text: "Cancel",
id: "cancel-reject"
}
}
});
$("#btn-reject").click(function (e) {
e.preventDefault();
$("#reject-dialog").dialog('open');
});
$('#cancel-reject').click(function () {
$("#reject-dialog").dialog('close');
console.log('confirm');
});
$('#confirm-reject').click(function () {
$("#reject-dialog").dialog('close');
console.log('reject');
});
}); //dom
</script>
JQuery versions:
you are binding to buttons that don't exist yet on document.ready.
instead you can tell the dialog what callback to trigger while creating the buttons.
Update:
according to the Jquery-ui documentation, dialog buttons options are accepted in one of the two following formats:
1) Object: The keys are the button labels and the values are the callbacks for when the associated button is clicked.
2) Array: Each element of the array must be an object defining the attributes, properties, and event handlers to set on the button.
i updated the code to reflect that.
code
<script type="text/javascript">
$(document).ready(function () {
var dialogDiv = $("#reject-dialog");
dialogDiv.dialog({
autoOpen: false,
modal: true,
buttons: [
{
text: "OK",
id: "confirm-reject",
click: function() {
dialogDiv.dialog("close");
console.log('confirm');
}
},
{
text: "Cancel",
id: "cancel-reject",
click: function(){
dialogDiv.dialog("close");
console.log('reject');
}
}
]
});
$("#btn-reject").click(function (e) {
e.preventDefault();
dialogDiv.dialog('open');
});
}); //dom
</script>
You need to use .on()'s event delegation since the buttons don't exist when the code is executed.
For example, change:
$('#cancel-reject').click(function () {
$("#reject-dialog").dialog('close');
console.log('confirm');
});
to:
$(document).on('click','#cancel-reject', function () {
$("#reject-dialog").dialog('close');
console.log('confirm');
});
jsFiddle example
Ideally you want to bind to an element that already exists on the page that's closer than document for better performance.
You need to inform a click function, even you need to bind a click handler after the create the dialog. I think this happens because Jquery tries to execute the attribute click through apply native js function and, if you don't define it, js try to execute apply in a undefined.
So, I suggest that you define an empty function (or jQuery.noop):
"Confirm": {
text: "OK",
id: "confirm-reject",
click: function(){} // or jQuery.noop()
}

jQuery dialog button how to set the click event?

Ok i got this code:
$(document).ready(
function() {
$(".dialogDiv").dialog({
autoOpen: false,
modal: true,
position: [50, 50],
buttons: {
"Print page": function() {
alert("Print");
},
"Cancel": function() {
$(this).dialog("close");
}
}
}
);
$('.ui-dialog-buttonpane button:contains("Print page")').attr("id", "dialog_print-button");
$(".dialogDiv").parent().appendTo($('form'));
}
How do I assign or set a new function to the click event?
$("#dialog_print-button"). ???
Edit, This works:
$("#dialog_print-button").unbind("click").click(
function () {
alert("new function that overide the old ones")
}
)
Tried to find how to do in the jQuery documentation but I think it's hard to find around in the documentation. Especially when new to javaScript and the jQuery libary.
Edit, A fast way to get help is to go to jQuery irc channel :D
I think this would help:
$(".dialogDiv").dialog("option", "buttons", {
"Print page": function() { /* new action */ },
"Cancel": function() { $(this).dialog("close"); }
});
Because buttons property sets all the buttons, you have to include cancel button handler.
$("#Print page").click(function () {
...
});
Or maybe it should be
$("#dialog_print-button").click(function () {
...
});
jQuery UI dialog buttons now supports the "id" attribute natively.
$("#dialog-form").dialog({
autoOpen: false,
height: "auto",
width: 300,
buttons:
[
{
text: "Create Revision",
id: "btnCreateRev",
click: function () {
//code for creating a revision
}
},
{
text: "Cancel",
id: "btnCancel",
click: function () { $(this).dialog("close"); },
}
]
});
You put the code within the button section:
...
buttons: {
"Print page": function() {
//here you execute the code or call external functions as needed
}
Once you click the button on the Dialog, that code is automatically invoked.
Therefore you insert there directly the code that implements your logic.

How to refresh changed buttons in jQuery UI dialog?

I have a jQuery UI dialog which is initialized
$('#jqDialog').dialog({
autoOpen: false,
modal: true,
resizable: false,
buttons: { 'Ok': function () { $(this).dialog('close'); } },
});
and then I want to change the buttons programatically w/o re-initializing the plugin instance.
$('#jqDialog')
.dialog('options',
{
buttons: {
'Ok': function () {
$(this).dialog('close');
store(id);
},
'Cancel': function () { $(this).dialog('close'); }
}
})
.dialog('open');
When the dialog window is opened it still have the original button. With the Button plugin you have to call .button("refresh"). Is there a similar method that needs to be called with the Dialog plugin?
What you have just needs a tweak, the method name is 'option' (no s) like this:
.dialog('option',
This works even when the dialog's open, you can test it out here.
You could destroy the dialog first by calling $dlg.dialog('destory'). and reevaluate the dialog you want.
The only wrong thing in your code is the use of the word options instead of option as in the following code
$("jqDialog").dialog("option", "buttons",
{
"Ok": function() {
$(this).dialog("close");
}
});

Categories

Resources