Jquery: Passing a function to a function which isnt required - javascript

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
});
}

Related

javascript 2 url from 1 button

Im working with Zend_Framework, and i need a little help.
I got this in my controller :
$link= new Zend_Form_Element_Button(
'lien_consigne',
array(
'label' => 'link',
'onClick' => 'gestion_lien_consigne()',
)
);
$this->addElement($link);
I would like my button redirect on 1 choosen link to the value of an other value named id_profil.
My javascript function :
function gestion_lien_consigne()
{
var value = $("select#profil_id").val();
if(value == "1")
document.getElementById("lien_consigne").onClick="javascript:window.open('http://google.com)";
else
document.getElementById("lien_consigne").onClick="javascript:window.open('http://yahoo.com)";
}
Right now, the button is displayed on my site, but when i click on this, nothing happens. Have u an idea why this is not working?
PS: I hope you can understand my English, i'm really sorry for this.
Simply open the required URL in window.open. In your code you are trying to change the onclick attribute of the button which will not have any visual effect. So modify your function like below:
function gestion_lien_consigne()
{
var value = $("select#profil_id").val();
if(value == "1")
window.open('http://google.com');
else
window.open('http://yahoo.com');
}
try
function gestion_lien_consigne() {
var value = $("select#profil_id").val();
if (value == "1") {
$("#lien_consigne").on('click', function() {
window.open('http://google.com');
});
} else {
$("#lien_consigne").on('click', function() {
window.open('http://yahoo.com');
});
}
}

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

Dialog returning before selecting answer

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.

Replacement of alert/prompt/confirm dialog boxes

I want to replace the default alert/prompt/confirm with my own and do not want to use a plugin. I did the styling but enable to figure out the action when the buttons are clicked (Ok/cancel/etc..). Here my code so far.
function jPromt(title,content,type,callback){
var alert = $('.resources').find('.alert').clone(); //basic barebone
alert.find('h3').html(title);
alert.find('.content').prepend(content);
var options = {
"_prompt" : {"OK" :""},
"_confirm": {"No" :"recomended", "Yes":""},
"_input" : {"Cancel":"recomended", "OK" :""}
}
for (var prop in obj) { // Create buttons
if (obj.hasOwnProperty(prop)) {
var btn = "<button class='button_"+prop+" "+obj[prop]+"'>"+prop+"</button>";
alert.find('.buttons').append(btn);
}
}
$('.resource_loader').append(alert)
$('body').append(alert).center().fadeIn('fast');
// This is here I'm not realy sure what to do whit callbaks for each button.
//if (callback && typeof(callback) === "function") {
// callback();
//}
}
I want it so that you can call jPromt() and the callback for each buttons will execute like so: or similar to it:
....
'ok', function(){
//do stuff if ok was clicked
},
'cancel', function(){
// canel was clicked, do stuff
}
JSFiddle: http://jsfiddle.net/CezarisLT/u6AYe/5/
Thank you in advance. I will surely select your answer as correct.
You can make that work with only a few modifications:
Pass an object as the callback parameter (I'd rename it to callbacks), where the keys represent the buttons, using the same format you defined for the options ("Yes", "No" etc). your call should look like this:
jPromt("test THE title","testing the contents","_confirm", {
'No' : function(){
alert("testing NO");
},
'Yes' : function(){
alert("testing YES");
}
});
Make btn a jQuery object inside your loop over obj, so you can attach a handler
Check if the callbacks parameter has a handler for the current prop; if yes, attach to btn.
Demo: http://jsfiddle.net/u6AYe/7/
What you can do is...
give your buttons actual click handlers invoking the callback
in your callback you inspect which button was actually clicked
Something like...
function jPromt(title,content,type,callback){
var myAlert = $('.resources').find('.alert').clone(); //basic barebone
myAlert.find('h3').html(title);
myAlert.find('.content').prepend(content);
var options = {
"_prompt" : {"OK" :""},
"_confirm": {"No" :"recomended", "Yes":""},
"_input" : {"Cancel":"recomended", "OK" :""}
};
if( options.hasOwnProperty(type) ){
obj = options[type];
}
for (var prop in obj) { // Create buttons
var $btn = $("<button class='button_"+prop+" "+obj[prop]+"'>"+prop+"</button>");
$btn.attr('btn-type',prop.toUpperCase());
myAlert.find('.buttons').append($btn);
$btn.click(callback);
}
$('body').append(myAlert.show());
}
jPromt("test THE title","testing the contents","_confirm",
function(){
answer = $(this).attr('btn-type');
if(answer == 'YES'){
alert("Yes!");
}else{
alert("No!");
}
}
);
See http://jsfiddle.net/u6AYe/8/ ...

How to handle alert in UI Automation using javascript?

In my application after tapping on a one button it gives and alert.There are two button on alert window: 1. Cancel 2. Ok
I have tried to tap on OK by using the solution given on the forum but it dosen't work.
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title '" + title + "' encountered!");
if (title == "Attention")
{
alert.buttons()["OK"].tap();
return true; // bypass default handler
}
return false; // use default handler
}
Function for handling alert dosen't called.Can anyone help me on this issue?
Thanks in advance.
UIATarget.onAlert = function onAlert(alert)
{
UIATarget.localTarget().delay(1);
UIALogger.logMessage("alertShown");
target.captureScreenWithName("AlertCaptured");
return true;
}
app.alert().buttons()["OK"].tap();
My solution to this problem was to add an one second delay after the function that handles the alert. You can not end your script with that function.
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title '" + title + "' encountered.");
if (title == "Are you sure you want to delete this?") {
alert.buttons()["Delete"].tap();
return true; //alert handled, so bypass the default handler
}
return false;
}
target.delay(1);

Categories