I am trying to display the Jquery dialog when the JSP loads. I check for a flag from the bean (showPopupFlag), so this is different from user clicking a button on a already loaded page.
I am trying to push some data into the pop when it displays using the dialogContent.
Is this possible to send/push data to the dialog (I know it is) but some how I am missing something. Any help is appreciated. - Thanks
My html code is
<div id="dialogId" title="JqueryDialogTest">
<div id="dialogContent"></div>
</div>
My included Js is
$(document).ready(function () {
$(function(){
$("#dialogId")
.dialog({autoOpen: false, modal : true} );
} );
});
$(function(){
if($("#showPopupFlag").val() === "true") {
$("#dialogContent").html($("#displaySubjectNotFoundPopup").val());
$("#dialogId").dialog("open");
}
});
You are messing up the auto execute function and the document ready block. So you can do achieve it by :
//document ready block
$(document).ready(function () {
//initialize the dialog ui box
$("#dialogId").dialog({
autoOpen: false,
modal: true
});
//auto executing function
//or you could simply remove the function and let the code block be executed on document ready
(function(){
if($("#showPopupFlag").val() == "true") {
$("#dialogContent").html("someValue");
$("#dialogId").dialog("open");
}
}());
});
And here is the demo JSFIDDLE
I call content for modal dialog from ajax
$.ajax({
url: "/Clerk/PauseServiceDialog",
success: function (data) {
$("body").append(data);
$("#pauseServiceDialog").modal({ keyboard: false });
}
});
When I close modal I use this code
$(document).on('hidden.bs.modal', ".modal", function (e) {
this.remove();
});
In firebug I see html code is deleted. But if I again call dialog and use some event I get 2 event. How I understand modal dialog do not correct deleted from DOM.
I found answer how fix duplicate event.
$(document).on('hidden.bs.modal', ".modal", function (e) {
var name = "#" + $(this).find("button.btn-primary").attr("id");
$("body").off("click", name);
$(this).remove();
});
You can hide modal by code
$("#pauseServiceDialog").data('bs.modal').hide()
P.S. sorry, i didn't understand notation $(document).on('hidden.bs.modal' in general - you should delete modal element AND object which handle its events ( it stored at $("#pauseServiceDialog").data('bs.modal') )
I have a anchor tag in my page for logout.
<a href="/logout/" id="lnk-log-out" />
Here I am showing a Popup for confirmation with jQuery UI dialog.
If user click Yes from dialog it has to execute the link button's default action, I mean href="/logout".
If No clicked a Popup box should be disappeared.
jQuery Code
$('#lnk-log-out').click(function (event) {
event.preventDefault();
var logOffDialog = $('#user-info-msg-dialog');
logOffDialog.html("Are you sure, do you want to Logout?");
logOffDialog.dialog({
title: "Confirm Logout",
height: 150,
width: 500,
bgiframe: true,
modal: true,
buttons: {
'Yes': function () {
$(this).dialog('close');
return true;
},
'No': function () {
$(this).dialog('close');
return false;
}
}
});
});
});
The problem is I am not able to fire anchor's href when User click YES.
How can we do this?
Edit: Right now I managed in this way
'Yes': function () {
$(this).dialog('close');
window.location.href = $('#lnk-log-out').attr("href");
}
In the anonymous function called when 'Yes' is fired, you want to do the following instead of just returning true:
Grab the href (you can get this easily using $('selector').attr('href');)
Perform your window.location.href to the url you grabbed in point 1
If you want the a tag to just do it's stuff, remove any preventDefault() or stopPropagation(). Here I have provided two different ways :)
Don't use document.location, use window.location.href instead. You can see why here.
Your code in the 'Yes' call should look something like, with your code inserted of course:
'Yes': function () {
// Get url
var href = $('#lnk-log-out').attr('href');
// Go to url
window.location.href = href;
return true; // Not needed
}, ...
Note: Thanks to Anthony in the comments below: use window.location.href = ... instead of window.location.href(), because it's not a function!
I have used this in many of my projects so i suggest window.location.href
'Yes': function () {
$(this).dialog('close');
window.location.href="your url"
return true;
},
The short question is when I fill a <div> containing a type=submit button the .click(function(){...} function fails.
What I'm doing is this, #formDialogButton opens #accordion populated by .ajax() containing #userForm with an input type=submit. When client clicks submit it is supposed to fire .ajax() where php does database stuff and returns one of the #userform.
$(".formDialogButton").click(function(){
var userDialog = "#" + this.id + "Dialog";
$("#userForm, #siteForm, #limitForm").html("<img src='ajax-loader.gif' />");
$("#userForm, #siteForm, #limitForm").load("ajax.php", {op: "forms"}, function(responseTxt,statusTxt,xhr){
$("#userForm").html($("#user").html());
$("#siteForm").html($("#site").html());
$("#limitForm").html($("#limit").html());
if(statusTxt=="success") {
$(userDialog).dialog({
autoOpen: false,
draggable: true,
modal: true,
resizable: true,
width: 700,
position: { within: "#mainContent" }
});
$(userDialog).dialog("open");
$( "#accordion").accordion({
collapsible: true,
heightStyle: "content",
});
};
if(statusTxt =="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
This is working and returns a <input class="submitAndReturn" type="submit" value="Submit" /> in the form. But I can't "find" it to do anything.
$(".submitAndReturn").click(function() {
alert ('this is where I call my regular .formSubmitButton and let success: function() do a .formDialogButton ');
});
I'm a total self taught amateur so please forgive me and try to help. Thanks
Sounds like you are trying to add the click event before the element is loaded on the page. Change
$(".submitAndReturn").on("click", function() {
alert ('as .submit and return is dynamically loaded. so, use on function');
});
to
$(document).on("click", ".submitAndReturn", function(e) {
e.preventDefault(); //cancel the click action if needed
alert ('as .submit and return is dynamically loaded. so, use on function');
});
$(".submitAndReturn").on("click", function() {
alert ('as .submit and return is dynamically loaded. so, use on function');
});
What I'm doing is this, #formDialogButton opens #accordion populated by .ajax() containing #userForm with an input type=submit
If I understand it correct .formDialogButton DOM element is getting loaded in .ajax() callback event.
If you are loading the javascript in question above in header or at the page end, most likely the $(".formDialogButton").click(function() event is not getting attached to DOM.
This happens because the script has already fired before the AJAX has fetched the required DOM to which event has to be attached. You would need to attach the event in .ajax() success callback. Something like
$.ajax({
url: 'YOUR_URL_TO_FETCH_FORM',
success: function(data) {
// associate click
$(".formDialogButton").click(function() // rest of the code
}
});
Currently, I'm working to replace "alert'/"confirm" with the jquery dialog.
But most of legacy codes is written in some asynchronous way, which make it difficult to change. Is there any way to make jquery dialog work in a synchronous way? ( don't use loop or callback function )
For example:
function run()
{
var result = confirm("yes or no");
alert( result );
\\more codes here
}
In this example the alert and other codes will be executed after user's choice.
If we use jquery dialog
var result = $dialog.open()
It will continue to execute the alert, which is asynchronous.
Currently, my solution is to use call back function in the OK|Cancel function.
For example:
OK: function ()
{
$dialog.close();
alert("yes");
//more codes here
}
This method works but it is difficult to make all the synchronous codes become asynchronous, which requires a lot of change (see the following example). So I'm looking for the synchronous jQuery Dialog, is it possible??
For example: ( The real codes are much more complicated than the following example)
function f1()
{
if ( confirm("hello") ) f2();
alert("no");
}
function f2()
{
if( confirm("world") ) f3();
alert("no");
}
function f3()
{
return confirm("!") ;
}
Another example:
vendorObject.on('some-event', function() {
if(confirm("Do you really want to do that?")) {
return true;
}
else {
return false; // cancel the event
}
});
... here the vendor object fires an event, which has to be cancelled if the user confirms. The event can only be cancelled if the event handler returns false - synchronously.
The short answer is no, you won't be able to keep your code synchronous. Here's why:
In order for this to be synchronous, the currently executing script would have to wait for the user to provide input, and then continue.
While there is a currently executing script, the user is unable to interact with the UI. In fact, the UI doesn't even update until after the script is done executing.
If the script can't continue until the user provides input, and the user can't provide input until the script is finished, the closest you'll ever get is a hung browser.
To illustrate this behavior, debug your code and set a break point on the line following a line that changes the UI:
$("body").css("backgroundColor", "red");
var x = 1; // break on this line
Notice that your page background is not yet red. It won't change to red until you resume execution and the script finishes executing. You are also unable to click any links in your page while you've got script execution paused with your debugger.
There is an exception to this rule for alert() and confirm(). These are browser controls, and are treated differently than actual web page UI elements.
The good news is that it really shouldn't be very hard to convert your code. Presumably, your code currently looks something like this:
if (confirm("continue?")) {
// several lines of code if yes
}
else {
// several lines of code if no
}
// several lines of code finally
Your asynchronous version could create a function ifConfirm(text, yesFn, noFn, finallyFn) and your code would look very much the same:
ifConfirm("continue?", function () {
// several lines of code if yes
},
function () {
// several lines of code if no
},
function () {
// several lines of code finally
});
Edit: In response to the additional example you added to your question, unfortunately that code will need to be refactored. It is simply not possible to have synchronous custom confirmation dialogs. To use a custom confirmation dialog in the scenario where an event needs to either continue or cancel, you'll just have to always cancel the event and mimic the event in the yesFn callback.
For example, a link:
$("a[href]").click(function (e) {
e.preventDefault();
var link = this.href;
ifConfirm("Are you sure you want to leave this awesome page?", function () {
location.href = link;
});
});
Or, a form:
$("form").submit(function (e) {
e.preventDefault();
var form = this;
ifConfirm("Are you sure you're ready to submit this form?", function () {
form.submit();
});
});
I'm not exactly sure what the motivation behind not using callbacks is so it is hard to judge what solution might satisfy your requirements, but another way to delay execution is through jQuery's "deferred" object.
http://api.jquery.com/category/deferred-object/
You could set up a function that opens the jquery dialog and add code that "waits" for dialog to close. This ends up working in a fairly similar way to a callback in the case you've laid out but here is an example:
function confirm () {
var defer = $.Deferred();
$('<div>Do you want to continue?</div>').dialog({
autoOpen: true,
close: function () {
$(this).dialog('destroy');
},
position: ['left', 'top'],
title: 'Continue?',
buttons: {
"Yes": function() {
defer.resolve("yes"); //on Yes click, end deferred state successfully with yes value
$( this ).dialog( "close" );
},
"No": function() {
defer.resolve("no"); //on No click end deferred successfully with no value
$( this ).dialog( "close" );
}
}
});
return defer.promise(); //important to return the deferred promise
}
$(document).ready(function () {
$('#prod_btn').click(function () {
confirm().then(function (answer) {//then will run if Yes or No is clicked
alert('run all my code on ' + answer);
});
});
});
Here it is working in jsFiddle: http://jsfiddle.net/FJMuJ/
No, you can't do anything sync in Javascript (alert is breaking the rules, in fact). Javascript is built with "single threaded, async" in the core.
What you can do, though, is disable functionality of the underlying page (lightbox-like) so no event get triggered from the page until you don't take the dialog action, be it OK or Cancel. Thought this does not help you to get your sync code working. You have to rewrite.
Here's some ideas - what you actually want is to block your async event to make it look like sync. Here's some links:
Queuing async calls
Mobl
Narrative JavaScript
Hope this helps you further!!
To answer David Whiteman's more specific question, here's how I'm implementing a "deferred" postback for a LinkButton Click event. Basically, I'm just preventing the default behaviour and firing the postback manually when user feedback is available.
function MyClientClickHandler(event, confirmationMessage, yesText, noText) {
// My LinkButtons are created dynamically, so I compute the caller's ID
var elementName = event.srcElement.id.replace(/_/g, '$');
// I don't want the event to be fired immediately because I want to add a parameter based on user's input
event.preventDefault();
$('<p>' + confirmationMessage + '</p>').dialog({
buttons: [
{
text: yesText,
click: function () {
$(this).dialog("close");
// Now I'm ready to fire the postback
__doPostBack(elementName, 'Y');
}
},
{
text: noText,
click: function () {
$(this).dialog("close");
// In my case, I need a postback when the user presses "no" as well
__doPostBack(elementName, 'N');
}
}
]
});
}
You can use a real modal dialog.
[dialog] is an element for a popup box in a web page, including a modal option which will make the rest of the page inert during use. This could be useful to block a user's interaction until they give you a response, or to confirm an action.
https://github.com/GoogleChrome/dialog-polyfill
I don't really see why you are opposed to using Jquery callbacks to achieve the behavior in your example. You will definitely have to rewrite some code but something like:
function f1() {
$( "#testdiv" ).dialog({
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
f2();
},
Cancel: function() {
$( this ).dialog( "close" );
alert('no');
}
}
});
}
function f2() {
$( "#testdiv2" ).dialog({
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
f3();
},
Cancel: function() {
$( this ).dialog( "close" );
alert('no');
}
}
});
}
function f3() {
$( "#testdiv3" ).dialog({
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
<div id="testdiv" title="Hello"/>
<div id="testdiv2" title="World"/>
<div id="testdiv3" title="!"/>