Dialog returning before selecting answer - javascript

I have a dialog box that pops up asking the user a question, this is in a function as below:
function confirmBox2(action) {
var message = "";
if (action == "Quit") {
message = "Are you sure you want to quit without saving?";
}
else if (action == "Delete") {
message = "Confirm you want to Delete?";
}
else if (action == "Save") {
message = "Are you sure you want to Save Changes?";
}
$('body').append('<div id="dialog-box" style="display:none;">' + message + '</div>');
$('#dialog-box').dialog({
modal: true,
buttons: {
Yes: function () {
$(this).dialog("close");
$('#dialog-box').remove();
return true;
//history.back(-1);
},
NO: function () {
$(this).dialog("close");
$('#dialog-box').remove();
return false;
}
}
});
}
You will see that the Yes returns true and the No returns false. I want to be able to do something like
if(confirmBox2("Quit")){
// do something here
}
The issue I am having is that the code is running asynchronously and not waiting for the dialog answer to be selected, how do I get round this?
Thanks

I've modified the confirmation function to accept 2 further parameters. One of them is the name of the function to call when you click "yes", and the other is the name of the function to call when you click "no". Your previous version was opening the dialog and then immediately ending the function, as the dialog call is not a blocking or synchronous call, so the function didn't wait till you closed the dialog before returning. That's why you weren't getting a result. With this method you create a function to handle the "yes" click, a function to handle the "no" click and you call them when the corresponding button is clicked.
function confirmBox2(Action, YesCallback, NoCallback) {
var message = "";
if (Action == "Quit") {
message = "Are you sure you want to quit without saving?";
} else if (Action == "Delete") {
message = "Confirm you want to Delete?";
} else if (Action == "Save") {
message = "Are you sure you want to Save Changes?";
}
$('body').append('<div id="dialog-box" style="display:none;">' + message + '</div>');
$('#dialog-box').dialog({
modal: true,
buttons: {
"Yes" : function () {
$(this).dialog("close");
$('#dialog-box').remove();
YesCallback();
},
"No" : function () {
$(this).dialog("close");
$('#dialog-box').remove();
NoCallback();
}
}
});
}
function onDialogYes() {
// handle the "yes" click here
}
function onDialogNo() {
// handle the "no" click here
}
confirmBox2("Quit", onDialogYes, onDialogNo);
You could alternatively do it without passing the callback functions as parameters, like this...
function confirmBox2(Action) {
var message = "";
if (Action == "Quit") {
message = "Are you sure you want to quit without saving?";
} else if (Action == "Delete") {
message = "Confirm you want to Delete?";
} else if (Action == "Save") {
message = "Are you sure you want to Save Changes?";
}
$('body').append('<div id="dialog-box" style="display:none;">' + message + '</div>');
$('#dialog-box').dialog({
modal: true,
buttons: {
"Yes" : function () {
$(this).dialog("close");
$('#dialog-box').remove();
onDialogYes();
},
"No" : function () {
$(this).dialog("close");
$('#dialog-box').remove();
onDialogNo();
}
}
});
}
function onDialogYes() {
// handle the "yes" click here
}
function onDialogNo() {
// handle the "no" click here
}
confirmBox2("Quit");
You'll probably want to pass Action into the event handlers for the buttons, so that you know what action you're dealing with.

Related

Why I need to click the button twice before it gets working?

Why I need to click the button twice before it gets working?
Function checks invalid input fields and passes sweetalert message when button is clicked.
document.addEventListener('invalid', (function() {
return function(e) {
e.preventDefault();
$('#submit').on("click", function() {
let valid = true;
$('[required]').each(function() {
if ($(this).is(':invalid') || !$(this).val()) valid = false;
})
if (!valid) swal({
title: "Good job",
text: "You clicked the button!",
type: "success"
}, );
})
};
})(), true);

Before saving the data Closing popup window show alert message?

In popup page after enter the data before clicking the save button user try to close the popup in (X mark) i want to show the alert message(You did not save your changes). if user click the save button no need to show the alert message.
using javascript how can i do this ?
<script type="text/javascript">
$(document).ready(function () {
var unsaved = false;
$('#Button1').click(function () {
unsaved = true;
});
function unloadPage() {
if (unsaved) {
return "You have unsaved changes on this page.?";
}
}
window.onbeforeunload = unloadPage;
});
</script>
used below technique may be it is useful
var is_template_save;
if (is_need_save == '0') {
is_template_save = false;
} else {
is_template_save = true;
}
window.onbeforeunload = function () {
if (is_template_save) {
return "Did you save your template?"
}
}
function template_save() {
is_template_save = false;
}
function template_unsave() {
is_template_save = true;
}
Hope it make sense

Server click executes before user click on confirmation dialog

I work with ASP.NET
I have some button "Delete" which remove users.
<asp:LinkButton ID="lnkDeleteUser" runat="server" OnClientClick="return ValidateDeleteUser();" OnClick="lnkDeleteUser_Click" CssClass=" btn btn-primary" Text="Delete"></asp:LinkButton>
My ValidateDeleteUser-function looks like :
function ValidateDeleteUser() {
if ($("#hdnNewUserFlag").val() != "Update") {
Dialogs.Alert("Please select user", null, null);
return false;
}
function okCallBack() {
return true;
}
function cancelCallBack() {
return false;
}
if ($("#hdnNewUserFlag").val() == "Update") {
Dialogs.Confirmation("Are you sure you want to Delete this User?", okCallBack, cancelCallBack, null);
}
}
where Dialogs.Confirmation - is my custom confirm-dialog.
var Dialogs = new function() {
var todo = null;
function getConfirmModalDialog(title, textBody) {
// create layout of dialog
return dialog;
};
function getConfirmationtDialog(title, msg, okCallBack, cancelCallBack, callBackObj) {
var ConfirmationDialog = $('#confirm-dialog');
if (ConfirmationDialog.length == 0) {
ConfirmationDialog = getConfirmModalDialog(title, msg);
} else {
$('.modal-title', ConfirmationDialog).html(title);
$('.modal-body', ConfirmationDialog).html(msg);
}
$('.ok-btn', ConfirmationDialog).unbind('click').click(function(e) {
e.preventDefault();
if (typeof okCallBack === "function") {
todo = okCallBack(callBackObj);
}
ConfirmationDialog.modal('hide');
});
$('.cancel-btn', ConfirmationDialog).unbind('click').click(function(e) {
e.preventDefault();
if (typeof cancelCallBack === "function") {
todo = cancelCallBack(callBackObj);
}
ConfirmationDialog.modal('hide');
});
return ConfirmationDialog;
};
this.Confirmation = function (dialogMsg, okCallBack, cancelCallBack, callBackObj) {
var dlg = getConfirmationtDialog('Confirmation', dialogMsg, okCallBack, cancelCallBack, callBackObj);
dlg.modal('show');
};
}
My problem is next : when user clicks on "Delete" Button, confirmation dialog opens and after this server side click executes, before user clicks on confirm-Ok-button.
I guess that what you want to do is make the confirm button on the dialouge dot he postback to the server and not have the link button do the postback to the server.
The problem is that you are not using a return false like this.
if ($("#hdnNewUserFlag").val() == "Update") {
Dialogs.Confirmation("Are you sure you want to Delete this User?", okCallBack, cancelCallBack, null);
return false;
}
On calling Dialogs.Confirmation, the modal gets opened and the buttons get click. But nowhere are you telling your function to wait for the click event. So after executing the JavaScript code, the server-side event will be executed.
Update: You should be returning false to the main function which calls Dialogs.Confirm. That is, ValidateDeleteUser as done above. Otherwise the main function will return true

Jquery: Passing a function to a function which isnt required

So I have a function that submits things through AJAX and then displays a dialog if it was successful or not. All works fine, but then I want the option of passing that dialog function an extra function (optional) which will carry out extra functions.
Here's what I have:
// the work
if (data._response.success == 'true') {
$("#suppliers_grid").trigger("reloadGrid");
$('#manage-suppliers-form').fullFormReset();
alertDialog('Supplier '+ action +' successfully!','Success',$('#manage-suppliers-form :input:visible:first').focus());
} else {
alertDialog('Supplier was not '+ action +' successfully!<br />Please try again or report this to the administrator.','Error','ui-state-error');
}
// the alertDialog function
function alertDialog(message,title,cssClass,closeFunction) {
title = typeof title !== 'undefined' ? title : 'Notice';
cssClass = typeof cssClass !== 'undefined' ? cssClass : 'ui-state-highlight';
if (cssClass=='ui-state-error') {
icon = 'ui-icon-alert';
}
else {
icon = 'ui-icon-info';
}
var dialog = $('<div><p><span class="ui-icon '+ icon +'"></span>'+ message +'</p></div>');
dialog.dialog({
modal: true,
title: title,
buttons: {
Ok: function() { $(this).dialog("close"); }
},
close: closeFunction()
});
}
1) The above doesn't work if I pass a closeFunction
2) Haven't even tested it -without- passing it something, but I'm sure it wouldn't work either. closeFunction should be OPTIONAL
3) I cant simply put the 'focus' line of code after the alertDialog call. Even though this works (gets focus in the background). As soon as someone clicks "ok" on the alertDialog, the focus is lost - so needs to be called on the close of the alertDialog.
First of all, whatever you mentioned in your question (Passing a function to a function) is called as "callback" function in the Javascript programming world.
Btw, to answer your question, I guess you need to bind the close event callback function that gets called when you close the dialog as follows:
var that = this;
dialog.dialog({
close: function( event, ui ) {
if(closeFunction && typeof closeFunction === 'function') {
closeFunction.call(that);
}
}});
Inside the closeFunction, try to do the focus() for the element required.
Try to read this! to get a better understanding on the close event callback usage.
If you still dont get a proper solution from my answer, please post a fiddle or give a better understanding of the problem your facing!
Try
// the work
if (data._response.success == 'true') {
$("#suppliers_grid").trigger("reloadGrid");
$('#manage-suppliers-form').fullFormReset();
//Pass the function as the fourth parameter and create a annonymous function to set the focus
alertDialog('Supplier '+ action +' successfully!', 'Success', '', function(){
$('#manage-suppliers-form :input:visible:first').focus();
});
} else {
alertDialog('Supplier was not '+ action +' successfully!<br />Please try again or report this to the administrator.','Error','ui-state-error');
}
// the alertDialog function
function alertDialog(message,title,cssClass,closeFunction) {
title = typeof title !== 'undefined' ? title : 'Notice';
cssClass = typeof cssClass !== 'undefined' ? cssClass : 'ui-state-highlight';
if (cssClass=='ui-state-error') {
icon = 'ui-icon-alert';
}
else {
icon = 'ui-icon-info';
}
var dialog = $('<div><p><span class="ui-icon '+ icon +'"></span>'+ message +'</p></div>');
dialog.dialog({
modal: true,
title: title,
buttons: {
Ok: function() { $(this).dialog("close"); }
},
close: closeFunction //assign the function reference instead of the return value of the function
});
}

How may I return true or false when I click on confirm dialog button?

I have a snippet of jQuery
$(function () {
$('.checked').click(function (e) {
e.preventDefault();
var dirtyvalue = "Test1";
var textvalue= "Test";
if (dirtyvalue.toLowerCase() != textvalue.toLowerCase()) {
{
var dialog = $('<p>Do you want to save your changes?</p>').dialog({
buttons: {
"Yes": function () {
dialog.dialog('close');
alert('yes btn called');
},
"No": function () {
dialog.dialog('close');
alert('No btn called');
},
"Cancel": function () {
dialog.dialog('close');
}
}
});
}
return false;
}
return true;
});
});
I want to return true or false on button click; 'Yes' should return true, 'No' should return true, and 'Cancel' should return false.
I already checked this link, but this is not solving my problem.
See also my previous question.
My scenario is that I have many ActionLink and TreeView links which navigate to their respective pages. Suppose I am on page 1 where I have this JS, and on that page I have many action links. Clicking on page 2, at that time my confirm should open, and when I click on the button 'No' it should redirect to page 2.
A dialog can't return a value, you must put what you want to do in another function. for example
var dialog = $('<p>Are you sure?</p>').dialog({
buttons: {
"Yes": function()
{
alert('you chose yes');
//call a function that redirects you
function_redirect(true);
},
"No": function()
{
alert('you chose no');
//call a function that redirects you
function_redirect(true);
},
"Cancel": function()
{
alert('you chose cancel');
//just close the dialog
dialog.dialog('close');
}
}
});
var function_redirect = function(redirect){
if(redirect === true){
//redirect to page2
}
}
you should put the logic you need to implement in "function_redirect" (or in whatever function you want) and pass parametrs according to the button pressed
EDIT - if you need to know what button has been clicked, just use the event object that is passed to the function
"Yes": function(e) {
//e.target is the element of the dom that has been clicked
//from e.target you can understand where you are and act accordingly
//or pass it to function_redirect
function_redirect(true, e.target);
var function_redirect = function(redirect, target){
if(redirect === true){
if($(target).parent().attr('id') === 'page2'){
//redirect to page2
}else{
//do something else
}
}
}
Dialog works async. So you cant return any value. You should use callback function.
$("a").click(dialog.dialog("open"),function(data){
//do your redirect here
})

Categories