How to create jQuery Dialog in function - jquery-ui

Does anyone know how to create a jQuery Dialog in a function? I can't find an attribute to set the message... In every example I found, the dialog has been statically written into the code in a div-tag. However, I want to create it dinamically, so I need to know how to create a dialog in a function.
It is no problem to set the title:
<script>
// increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 1000;
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
show: "blind",
hide: "explode"
});
$( "#opener" ).click(function() {
//$( "#dialog" ).dialog( "open" );
$( this ).dialog({ title: 'Please confirm deletion!' });
return false;
});
});
</script>
</head>
<body>
I have the documentation and some examples here.
Thanks for helping out guys.
Cheers,
doonot
============================= [SOLUTION]=====================================
Thanks for all who answered this questions. This is how i wanted it:
function createDialog(title, text) {
return $("<div class='dialog' title='" + title + "'><p>" + text + "</p></div>")
.dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Confirm": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
And it can be called for example like this (clicking on an image):
<img src="delete.png" onClick="createDialog('Confirm deletion!', 'Do you really want to delete this package?')">

function createDialog(title, text, options) {
return $("<div class='dialog' title='" + title + "'><p>" + text + "</p></div>")
.dialog(options);
}

Here is a simple example:
function openDialog(message) {
if ($('#dialog').length == 0) {
$(document.body).append('<div id="dialog">'+message+'</div>');
} else {
$('#dialog').html(message);
}
$( "#dialog" ).dialog({
autoOpen: false,
show: "blind",
hide: "explode"
});
$( "#dialog" ).dialog("open");
}

I used this with additionally jQuery tmpl plugin.
var confirmTemplate = jQuery.template("<div class='dialog' title='${title}'><p>${text}</p></div>");
function showDialog(options) {
if (options && options.data && options.dialog) {
var dialogOptions = jQuery.extend({}, { modal: true, resizable: false, draggable: false }, options.dialog);
return jQuery.tmpl(confirmTemplate, options.data).dialog(dialogOptions);
}
}
function hideDialog (item) {
if (!item.jQuery) item = $(item);
item.dialog("close").dialog("destroy").remove();
}
usage:
showDialog({
data: {
title: "My Title",
text: "my Text"
}
dialog: {
myDialog: "options"
}
});

Related

Send Jquery UI Dialog value to Url.Action

Not sure how to pass along a bool to my (working) C# method DeleteTestuser. I've Googled the heck out of this but mileage varies with all kinds of pitfalls, i.e. old information, bad syntax.
Rather than passing confirm as false, below, I need to return a bool if the user confirms the action. Thanks...
index.cshtml
<a href="#Url.Action("DeleteTestUser", "Home",
new {id = testUser.TestUserId, confirm = false})"
id="confirm-delete">
_layout.cshtml
<script type="text/javascript">
$(function () {
$('#dialog-modal').dialog(
{
title: 'Test User',
draggable: false,
resizeable: false,
closeOnEscape: true,
modal: true,
autoOpen: false,
buttons: {
'Yes': function () {
$(this).dialog('close');
confirmResult(true);
},
'No': function () {
$(this).dialog('close');
confirmResult(false);
}
}
});
$('#confirm-delete').click(function () {
$('#dialog-modal').dialog("open");
});
function confirmResult(result) { return result }
});
</script>
Basically, you're recreating your own confirm() with jQuery UI Dialog. I did this and here is a similar case: confirm form submit with jquery UI
Apply this to your scenario and you have something like:
$(function() {
function ui_confirm(message, callback) {
var dfd = $.Deferred();
var dialog = $("<div>", {
id: "confirm"
})
.html(message)
.appendTo($("body"))
.data("selection", false)
.dialog({
autoOpen: false,
resizable: false,
title: 'Confirm',
zIndex: 99999999,
modal: true,
buttons: [{
text: "Yes",
click: function() {
$(this).dialog("close");
dfd.resolve(true);
if ($.isFunction(callback)) {
callback.apply();
}
}
}, {
text: "No",
click: function() {
$(this).dialog("close");
dfd.resolve(false);
}
}],
close: function(event, ui) {
$('#confirm').remove();
}
});
dialog.dialog("open");
return dfd.promise();
}
function deleteUser(id){
// Code you will execute to delete a user or POST back.
}
$(".button").button();
$('.del').click(function(e) {
e.preventDefault();
// your code
$.when(ui_confirm("Are you sure?")).done(function(val) {
if (val) {
console.log("Delete User Confirmed.");
deleteUser($(this).attr("id"));
} else {
console.log("Do not delete user.");
}
});
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
John Smith Delete
You may be able to get away with just executing specific callbacks. That's up to you. This code can then also be used to pass along another function or to use with a prompt() like dialog.
Update
See: Using Url.Action in javascript
For example:
function deleteTestUser(uid, conf){
var url = '#Url.Action("DeleteTestUser", "Home", new {id=' + uid + ', confirm=' + conf + '})';
$.get(url, function(data){
console.log("User " + uid + " Deleted.");
});
}
I would use POST if possible.
function deleteTestUser(uid, conf){
$.post('#Url.Action("DeleteTestUser", "Home")', { id: uid, confirm: conf }, function(data){
console.log("User " + uid + " Deleted.");
});
}

Pass a variable to JQuery UI dialog

I am deleting a record using PHP. I want to use a JQuery UI dialog to confirm the action, but I dont know how to pass a variable (my RecordID) to the redirect URL function, or allow the URL to access window.location.href.
$("#confirm" ).dialog({
resizable: false,
autoOpen: false,
modal: true,
buttons: {
'OK': function() {
window.location.href = 'url and myvar??';
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
}
});
$("#delete").click(function() {
$("#confirm").dialog( "open" ).html ( "Are U Sure?" );
return false;
});
HTML
<a href='index.php?recordid=$row[recordid]' id='delete'>DELETE</a>
Is there a good way to do this?
You can try using the .data() method to store data for you. Take a look at this answer
Passing data to a jQuery UI Dialog
For example to pass a variable, you can store it using the data function, before opening the dialog
$("#dialog_div")
.data('param_1', 'whateverdata')
.dialog("open");
Then you can get this back by:
var my_data = $("#dialog_div").data('param_1')
You want to change the configuration of the dialog on click (in this case, the behaviour of the Ok button). For that your have many solutions all of them ugly (imo). I would advice generating a dialog on the fly, and destroying it once it has been used, something like this:
$("#delete").click(function(ev) {
ev.preventDefault(); // preventDefault should suffice, no return false
var href = $(this).attr("href");
var dialog = $("<div>Are you sure?</div>");
$(dialog).dialog({
resizable: false,
autoOpen: true,
modal: true,
buttons: {
'OK': function() {
window.location = href;
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
},
close: {
$( this ).remove();
}
});
});
Or even better, encapsulate the confirm dialog into a function so that you can reuse it, like so:
function confirmDialog(msg) {
var dialog = $("<div>"+msg+"</div>");
var def = $.Deferred();
$(dialog).dialog({
resizable: false,
autoOpen: true,
modal: true,
buttons: {
'OK': function() {
def.resolve();
$( this ).dialog( "close" );
},
'Cancel': function() {
def.reject();
$( this ).dialog( "close" );
}
},
close: {
$( this ).remove();
}
});
return def.promise();
}
And then use it like so
confirmDialog("are your sure?").done(function() {
window.location = $(this).attr("href");
}).fail(function() {
// cry a little
});
You may have to check if the deferred object has been rejected or resolved before you close the dialog, to ensure the confirm rejects on close (and not just on pressing the 'Cancel' button). This can be done with a def.state() === "pending" conditional.
For more information on jquery deferred: http://api.jquery.com/category/deferred-object/
Deleting actions probably shouldn't be done using a GET, but if you wanted to do it that way I would recommend using the $.data in jQuery so each link had a data-record-id attribute. Then on click of one of the links, it pops up the dialog and when confirmed it adds that to the URL, and redirects.
Example:
$(function(){
$(".deleteLink").click(function(){
var id = $(this).data("record-id");
var myHref = $(this).attr('href');
$("#confirmDialog").dialog({
buttons:{
"Yes": function()
{
window.location.href = myHref + id;
}
}
});
});
});
<a class="deleteLink" data-record-id="1">Delete</a>
...
<div id="confirmDialog">
<p>Are you sure?</p>
</div>
HTML
<a data-title="Title" data-content="content" data-mydata="1" class="confirmation-dialog" href="#">Link</a>
JS
$('.confirmation-dialog').confirm({
buttons: {
Yes: function(){
console.log(this.$target.attr('data-mydata'));
No: function(){
}
}
});

passing parameters to jquery ui dialog

I use .data like this to pass the id of the textbox that calls the dialog
$("#<%=txtDirProprio.ClientID%>").focus(function()
{
$("#<%=dialog.ClientID%>").dialog( "open" ).data("id","#<%=txtDirProprio.ClientID%>");
return false;
});
here is the code for the dialog
$("#<%=dialog.ClientID%>").dialog({
autoOpen: false,
show: "blind",
hide: "explode",
width: 800,
height:200,
modal: true,
buttons:
{
"Ajouter": function() {
$( this ).dialog( "close" );
StringBuilderDir($( this ).data("id"));
},
"Vider": function() {
$( this ).dialog( "close" );
$( $( this ).data("id") ).val("")
},
"Canceler": function() {
$( this ).dialog( "close" );
}
},
open: function()
{
var dir = $( $( this ).data("id") ).val().split("-");
if(dir[0] != "")
{
$("#<%=dd_dialog_directionvp.ClientID%> option").each(function(index)
{
if ($("#<%=dd_dialog_directionvp.ClientID()%> option")[index].text == dir[0])
{
$("#<%=dd_dialog_directionvp.ClientID()%> option")[index].selected = true;
}
})
}
}
});
So $ ( this ).data("id") returns the id of the textbox. It works fine except in the open function. The id is undefined
Why it works in the functions for the buttons but not in the open function. It looks like it's not the same 'this'
Thank you
$("#<%=txtDirProprio.ClientID%>").focus(function()
{
$("#<%=dialog.ClientID%>").data("id","#<%=txtDirProprio.ClientID%>").dialog( "open" );
return false;
});
Have to set the data first before calling .dialog('open');

How set the names of jquery-ui buttons on dialog window from variable?

jquery-ui dialog window in javascript:
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Ok": function() {
$( this ).dialog( "close" );
},
"Cancel": function() {
$( this ).dialog( "close" );
}
}
});
There two buttons "Ok" and "Cancel". On each button there function. Buttons names fastened hardly. There some ways to named buttons from variable?? like this:
var Button1 = "Ok";
var Button2 = "Cancel";
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
Button1: function() {
$( this ).dialog( "close" );
},
Button2: function() {
$( this ).dialog( "close" );
}
}
});
I try code above but buttons appear with names "Button1" and "Button2".
Can I also display images in buttons but not text???
Referring to http://jqueryui.com/demos/dialog/ you can see there are 2 alternate ways of defining the buttons, one is what you are using here, the second is using arrays.
var button1 = 'Ok';
var button2 = 'Not Ok';
$( ".selector" ).dialog({ buttons: [
{
text: button1,
click: function() { $(this).dialog("close"); }
},
{
text: button2,
click: function() { $(this).dialog('close'); }
}
] });
It looks like this must solve your problem.

Dynamically Set Title On Dialog

var dlg = $("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: {
'Update': function() {
alert(clientCode);
},
Cancel: function() {
$(this).dialog('close');
}
}
});
$(".edit").click(function() {
myval = $(this).parent().children('td:nth-child(1)').text();
dlg.dialog('open');
return false;
});
How do I take "myval" and have it as the title of the dialog? I've tried passing it as an argument when doing dlg.dialog('open', myval) and no luck. I've also tried passing it as a parameter but with no luck either. I'm probably doing things in the wrong way, however.
$("#your-dialog-id").dialog({
open: function() {
$(this).dialog("option", "title", "My new title");
}
});
create the dialog in the click-event and use this to set title:
something like this:
$(".edit").click(function() {
myval = $(this).parent().children('td:nth-child(1)').text();
var dlg = $("#dialog").dialog({
autoOpen: false,
title: myval,
modal: true,
buttons: {
'Update': function() {
alert(clientCode);
},
Cancel: function() {
$(this).dialog('close');
}
}
});
dlg.dialog('open');
return false;
});

Resources