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

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.

Related

Asp.net - Bootstrap confirmation - FullCalendar => singleton weird behavior

I' trying to implement Bootstrap confirmation
on top of FullCalendar
the code posted below works for basically everything
except when I set "singleton" to "true"
<script src="~/Scripts/jquery-3.3.1.slim.min.js"></script>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/umd/popper.js"></script>
<script src="~/Scripts/umd/popper.min.js"></script>
<script src="~/Scripts/jquery-ui.min.js"></script>
<script src="~/Scripts/bootstrap.bundle.js"></script>
<script src="~/Scripts/bootstrap-confirmation.js"></script>
<script src="~/Scripts/moment-with-locales.min.js"></script>
<script src="~/Scripts/fullcalendar/fullcalendar.min.js"></script>
<script src="~/Scripts/fullcalendar/locale-all.js"></script>
<script src="~/Scripts/jquery.signalR-2.4.0.min.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
hub = $.connection.planningHub;
hub.client.update = function (v, s, e, is, ie) {
fc.fullCalendar('refetchEvents');
};
$.connection.hub.start().done(function () {
fc = $('#calendar').fullCalendar({
defaultView: 'agendaWeek',
header: {
...
},
´
events: {
...
};
}
},
eventClick: function (calEvent, jsEvent, view) {
jsEvent.preventDefault();
var fcId = calEvent.id;
var eventTarget = jsEvent.target;
$(eventTarget).confirmation({
// MAYBE HERE!
rootSelector: eventTarget,
// MAYBE HERE!
placement: 'left',
title: 'do you want to delete?',
// HERE!
singleton: true,
// HERE!
popout: false,
onConfirm: function () {
$.post('#Url.Action("DeletePlanning")', { id: fcId}, function (r) {
switch ( r.status) {
case 'success':
fc.fullCalendar('refetchEvents');
break;
case 'error':
console.error(r.message);
rv();
break;
}
}
);
},
oncancel: function () { },
});
$(eventTarget).confirmation('show');
}
});
});
});
at that point it keep creating multiple popover,
with the difference that they close all at once when one closes.
Any Idea?
I really need it to be singleton!
(be forgiving, I'm really new in js and asp.net)
thanks in advance for the help

Merging two json file and using it in autocoplete plugin

I am trying to merge two JSON file and using it in autocompleteplugin.
But I do get an error TypeError: $(...).easyAutocomplete is not a function even I have added js library for both auto complete and jquery.
My code look like this:
<script src="jquery-3.1.0.js"></script>
<link href="easy-autocomplete.min.css" rel="stylesheet" />
<script src="jquery.easy-autocomplete.min.js"></script>
<script>
$.getJSON("file1.json", function (data1) {
$.getJSON("file2.json", function (data2) {
var final = $.extend({}, data1, data2);
var options = {
data: final,
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});
</script>
I made a working example based on your code.
Please check you have the correct paths when you include the script files. And also check if jQuery is included.
Hope will help you:
$.getJSON("https://api.myjson.com/bins/42jd0", function (data1) {
$.getJSON("https://api.myjson.com/bins/5bjqc", function (data2) {
var final = [];
final.push(data1.employees1);
final.push(data2.employees2);
var new_final = final[0].concat(final[1]);
var options = {
data: new_final,
getValue: "firstName",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/jquery.easy-autocomplete.min.js"></script>
<div class='easy-autocomplete'>
<input id="KUNDE"/>
</div>
You can run the code here by hitting the Run code snippet button or you can also check the jsfiddle I've made here.

jQuery UI: model dialog 'close'

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.

How do I get the onclick variable into a dialog function

I have a onclick event that has a value in it that I want to post to a backend php script. Just not sure how to get it in the dialog function.
function reorder(job_index)//<--------this fella
{
$('#dialog').dialog('open');
}
$(document).ready(function(){
$(function() {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function() {
var jobID=$("#jobnumber").val();
$.post("rpc.php", {
job_index:job_index,// <-------to here
jobID:jobID,
method: "reorder"
},
function(data,textstatus)
{
alert(data.message);
}, "json");
},
'No, create a new number for me': function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
});
});
The value is job_index. Any tips?
Thanks
In the below code, I'm using a single function that will allow you to both store and retrieve your index.
The function index is creating a closure by returning declaring and returning another function. This means that the variable _index will still be available (think of it as like the variable was allocated on the heap instead of the stack-frame; ie malloc-ed) once the (outer) function has returned, and as you can see the function is self-invoking, due to the }(); on the last line of the function, thus returning immediately during parsing.
Then when you call the function index again (which now you will be basically calling the inner function that takes one formal argument, ind), you can pass in your index and if you do, the function will store it in the _index variable that I mentioned earlier on...ie the variable that is still available after the outer function returned.
If you don't pass in an argument (ie invoke the function like such: index()), the function only returns your stored variable. The logic behind this is that if a parameter is not passed, the value of the actual argument is undefined. Thus the function checks if the value is undefined, and if it is, it justs returns your variable.
And btw, you have a nested ready function inside your outer ready function. This is because $(function() { is the same as $(document).ready(function(){. I fixed this in the below code:
var index = function () {
var _index;
return function (ind) {
if (typeof ind !== "undefined") {
_index = ind;
}
return _index;
};
}();
function reorder(job_index)
{
index(job_index);
$('#dialog').dialog('open');
}
$(function () {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function () {
var jobID = $("#jobnumber").val();
$.post("rpc.php", {
job_index: index(),
jobID: jobID,
method: "reorder"
},
function (data, textstatus) {
alert(data.message);
},
"json");
},
'No, create a new number for me': function () {
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog('close');
}
}
});
});
Another way to do it is by using the data method that nickf mentioned. This will allow you to store the index directly as part of your element, like such:
function reorder(job_index)
{
$('#dialog').data("job", job_index).dialog('open');
}
$(function () {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function () {
var jobID = $("#jobnumber").val();
$.post("rpc.php", {
job_index: $("#dialog").data("job"),
jobID: jobID,
method: "reorder"
},
function (data, textstatus) {
alert(data.message);
},
"json");
},
'No, create a new number for me': function () {
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog('close');
}
}
});
});
You could store it as data on the element using .data()
Create a global variable, store the last clicked job_index there, and read it from there in the click handler.
var last_job_index;
function reorder(job_index)
{
last_job_index = job_index;
$('#dialog').dialog('open');
}
//snip
$.post("rpc.php", {
job_index: last_job_index,
jobID: jobID,
method: "reorder"
},
Warning: This is quite an unprofessional solution (shared mutable state)

Problems with custom alert box via jqueryid dialog

I've been working on a custom alert box that has the same style as the rest of the website via jquery-ui. It was working well except that it wouldn't open more than once. As I was trying to fix that, I broke the whole thing some how, and now I get this error:
Node cannot be inserted at the specified point in the hierarchy" code: "3
Below is the code. doAlert() is a simple replacement for alert(). Later it will have more features. show_support() creates dialog box in a similar way to doAlert(), except that it works perfectly.
function doAlert(msg, title) {
var alert_box = $('body').append('<div id="alert_box" class="centered" style="padding:.5em;vertical-align:middle;display:none;"><p>' + msg + '</p></div>');
title = typeof(title) != 'undefined' ? title : 'Message';
alert_box.dialog({
modal: true,
title: title,
width: 400,
height: 150,
resizable: false,
overlay: {
opacity: 0.5,
background: 'black'
},
buttons: {
'Ok': function() {
$(this).dialog('close');
}
},
close: function() {
$(this).dialog('destroy').remove();
}
});
}
function show_support() {
var dialog = $('body').append('<div id="dialog_support" style="display:none;"></div>');
$('#dialog_support').load('/supporttracker', {action:'get_dialog'})
.dialog({
modal: true,
title: "Support",
width: 620,
height: 400,
buttons: {
"Send": function() {
if (!$('#issue_message').val()) {
doAlert('Your message cannot be blank. Please enter your message.');
return;
}
$.ajax({
type: 'POST',
url: '/supporttracker',
data: 'action=add_simple&'+$('#issue').serialize(),
success: function(msg){
doAlert('Thank you. We will get to your question/issue as soon as we can. Usualy within 24 hours.');
$('#dialog_support').dialog('close');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
doAlert('An error accured: '+textStatus);
}
});
},
"Cancel": function() {$(this).dialog('close');}
},
close: function() {
$(this).remove();
}
});
}
Anyone have any ideas of how I messed up doAlert?
Look at the close method. doAlert seems to be doing a dialog('destroy'), then calling remove on it. show_support is simply removing the dialog from the DOM. I don't know what the dialog method returns so it may be that the DOM element isn't actually getting removed and thus reinserting it fails -- since you can't have to elements with the same id.
If it were me I'd create the dialog on page load (hidden), then simply update a message when it needs to be shown, and use open/close to reuse the element rather than recreating it.
<div id="alert_box" class="alert-dialog" style="display: none;">
<p id="alert_message">An error occurred.</p>
</div>
<script type="text/javascript">
$(function() {
$('#alert_box').dialog({
modal: true,
width: 400,
height: 150,
resizable: false,
overlay: {
opacity: 0.5,
background: 'black'
},
buttons: {
'Ok': function() {
$(this).dialog('close');
}
}
});
});
function doAlert( msg, title )
{
$('#alert_message').html(msg);
$('#alert_box').attr( 'title', title )
.dialog('open');
}
</script>

Categories

Resources