This may be a easy answer-
In my JS I've replaced JS's confirm function with my own. Which basically and simply looks like this:
function confirm(i){
var options = '<br/><br/><input class="button1" value="Yes" type="button" onclick="return true"> <input class="button1" value="No" type="button" onclick="return false">';
$('#text').html(i+options);
$('#confirmDiv').fadeIn('fast');
}
Obviously the return true / false didn't work, or else I wouldn't be asking!
In another function i've got (So you get the picture):
var con = confirm("Are you sure you'd like to remove this course?");
if(!con){return;}
How can I get confirm to return the value directly? I'd assume it's return {this.value} or so?
Thanks!
Your problem is that your custom confirm isn't modal. That means that when your confirm is shown, the code runs on. There is no chance for you to wait for the user's choice within confirm() and return it from there.
As far as I know, there is no way to emulate the behaviour of a modal confirmation dialog in Javascript (except for the non-standard ShowModalDialog().)
The usual way of doing this is adding a function() { ... } callback to each button's click event, and doing whatever the "ok" click is supposed to do in there.
My way around this problem was to add some arbitrary data to the object, and check for that data on click. If it existed, proceed with the function as normal, otherwise confirm with a yes/no (in my case using a jqtools overlay). If the user clicks yes - insert the data in the object, simulate another click and wipe the data. If they click no, just close the overlay.
Here is my example:
$('button').click(function(){
if ($(this).data('confirmed')) {
// Do stuff
} else {
confirm($(this));
}
});
And this is what I did to override the confirm function (using a jquery tools overlay):
window.confirm = function(obj){
$('#dialog').html('\
<div>\
<h2>Confirm</h2>\
<p>Are you sure?</p>\
<p>\
<button name="confirm" value="yes" class="facebox-btn close">Yes</button>\
<button name="confirm" value="no" class="facebox-btn close">No</button>\
</p>\
</div>').overlay().load();
$('button[name=confirm]').click(function(){
if ($(this).val() == 'yes') {
$('#dialog').overlay().close();
obj.data('confirmed', true).click().removeData('confirmed');
} else {
$('#dialog').overlay().close();
}
});
}
I found another hacked solution to emulate the modale dialog like mentioned from Pekka 웃 before. If you break the JS execution there is no need to loop in a while(true). After retrieving the users input (click) we can go on with JS execution while calling the origin method again with eval and returning the users choice as boolean.
I created a small jsfiddle with jquery and notyjs to simply show my solution:
jsfiddle: Overriding native modal confirm alert
Here again the important code:
/** confirm as noty.JS **/
var calleeMethod2 = null;
var returnValueOfConfirm = null;
var args = null;
var calleeMethod = null;
var refreshAfterClose = null;
var savedConfirm = window.confirm;
window.confirm = function(obj) {
// check if the callee is a real method
if (arguments.callee.caller) {
args = arguments.callee.caller.arguments;
calleeMethod = arguments.callee.caller.name;
} else {
// if confirm is called as if / else - rewrite orig js confirm box
window.confirm = savedConfirm;
return confirm(obj);
}
if (calleeMethod != null && calleeMethod == calleeMethod2) {
calleeMethod2 = null;
return returnValueOfConfirm;
}
noty({
text: obj,
buttons: [{
text: 'Yes',
onClick: function($noty) {
$noty.close();
noty({
text: 'YES',
type: 'success'
});
}
}, {
text: 'No',
onClick: function($noty) {
$noty.close();
noty({
text: 'NO',
type: 'error'
});
}
}]
});
throw new FatalError("!! Stop JavaScript Execution !!");
}
function runConfirmAgain() {
calleeMethod2 = calleeMethod;
// is a method
if (calleeMethod != null) {
var argsString = $(args).toArray().join("','");
eval(calleeMethod2 + "('" + argsString + "')");
} else {
// is a if else confirm call
alert('confirm error');
}
}
Related
I have created custom dialogs like Alert and ConfirmDialog with Bootstrap and Jquery.
Here is sample : http://jsfiddle.net/eb71eaya/
Problem - in the callback I make an ajax call, and if it returns true - I show an alert with status success else - error. But this alert doesn't show while request makes delete. (In the example I don't make an ajax request, just show alert, but that also doesn't work.)
function getEsrbAlertDialog(title, msg, callBack, obj) {
var esrbAlertDialog = $('#esrb-dialog');
if (esrbAlertDialog.length == 0) {
esrbAlertDialog = getEsrbDialog(title, msg);
} else {
$('.modal-title', esrbAlertDialog).html(title);
$('.modal-body', esrbAlertDialog).html(msg);
}
$('.modal-footer div', esrbAlertDialog).empty();
$('.modal-footer div', esrbAlertDialog).append('<button class="btn btn-primary pull-right close-btn">Close</button>');
$('.close-btn', esrbAlertDialog).unbind('click').click(function () {
if (typeof callBack === "function") {
todo = callBack(obj);
}
esrbAlertDialog.modal('hide');
});
return esrbAlertDialog;
};
I want to execute callback when confirmation dialog become closed.
UPDATE : I understand logic like this : When user click on "Ok"-button, dialog must be closed. And when it is already closed then fire event 'hidden.bs.modal' which must execute callBack. But CallBack executes before confirm dialog finish hiding.
This line:
esrbConfirmationDialog.modal('hide');
Is hiding the second dialog.
EDIT:
Both dialogs use the same div as there reference:
var esrbAlertDialog = $('#esrb-dialog');
Create seperate dialogs one for the alert and one for confirmation.
Just replace this.Alert function to below code, i.e. just add e.preventDefault();
this.Alert = function (dialogMsg, callBack, obj) {
var dlg = getEsrbAlertDialog('Alert', dialogMsg, callBack, obj);
e.preventDefault();
dlg.modal('show');
};
I have a web application window where I'am required to press a button to remove some stuff many times (the button is easily click-able with JS by selecting it with getElementbyClassName()[i]). But after each click I have to manually press the "OK" button on the window.alert("Are you sure?"); box.
I can't change the websites mechanism as I'm not the owner or developer. But I want somehow to be able to automate this stuff.
JS I use for clicking on the element:
var el = document.getElementsByClassName('ruleAddButton');
for (var i = 0; i < el.length; i++) {
el[i].click();
}
Since alert is only to show info to the user (you can't get user input from an alert), I think you maybe want to monkey patch confirm function this way:
var originalConfirm = window.confirm;
window.confirm = function(msg) {
if (msg.match(/Are you sure/) {
// this confirm should return always true
return true;
} else {
// we want other confirms works as normal
return originalConfirm.bind(window)(msg);
}
}
Just in case, I would do the same trick for alert function
var originalAlert = window.alert;
window.alert = function(msg) {
if (msg.match(/Are you sure/) {
// this is what alert always returns after user clicks OK
return undefined;
} else {
// we want other alerts works as normal
return originalAlert.bind(window)(msg);
}
}
EDIT
Also, you can do something as simple as:
window.confirm = function() { return true; };
But on this case, be aware that ALL confirm calls will be intercepted
You can't click the OK button in a dialog created by window.alert. That dialog is created by the browser and is not controllable from the webpage's JavaScript context. However, what you can do is just monkey-patch the alert function to not show a dialog at all:
window.alert = function() {
// Do nothing.
};
You can override the alert function:
window.alert = function(){}
But it will disable all alerts on this page.
I have a series of buttons that execute different functions when clicked. The function checks whether the user is logged in, and if so proceeds, if not it displays an overlay with ability to log in/create account.
What I want to do is re-execute the button click after log-in, without the user having to reclick it.
I have it working at the moment, but I'm pretty sure that what I'm doing isn't best practice, so looking for advice on how I can improve...
Here's what I'm doing: setting a global variable "pending_request" that stores the function to be re-run and in the success part of the log-in ajax request calling "eval(pending_request)"
Example of one of the buttons:
jQuery('#maybe_button').click(function() {
pending_request = "jQuery('#maybe_button').click()"
var loggedin = get_login_status();
if (loggedin == true) {
rec_status("maybe");
}
});
.
success: function(data) {
if(data === "User not found"){
alert("Email or Password incorrect, please try again");
}else{
document.getElementById('loginscreen').style.display = 'none';
document.getElementById('locationover').style.display = 'none';
eval(pending_request);
pending_request = "";
}
}
Register a function to handle the click and then invoke that func directly without eval().
jQuery('#maybe_button').on('click', myFunction)
This executes myFunction when the button is clicked. Now you can "re-run" the function code every time you need it with myFunction().
And btw since you are using jQuery you can do $('#loginscreen').hide() where $ is an alias for jQuery that's auto defined.
EDIT
Please, take a look at the following code:
var pressedButton = null;
$('button1').on('click', function() {
if (!isLoggedIn()) {
pressedButton = $(this);
return;
}
// ...
});
And, in your success handler:
success: function() {
// ...
if (pressedButton) pressedButton.trigger('click');
// ...
}
When a user leaves a JSP page, I need to display a confirmation with yes no button "You have unsaved changes. Do you want to leave it without saving?". If the user presses "ok", then the user goes to the page s/he is navigating to. Otherwise, if "no" is pressed, the user stays on the page. My code is here:
var formdata_original=false;
jQuery(".outConfirmPlugin").click(function () {
if (formdata_original == false) {
con();
}
return formdata_original;
});
function con() {
$.confirm({
'title':'',
'message':settings.jsMessage,
'buttons':{
'Yes':{
'class':'blue',
'action':function () {
formdata_original = true;
}
},
'No':{
'class':'gray',
'action':function () {
}
}
}
});
};
I know my error is: function "con" and "return formdata_original;" - they are not synchronized. How can i do this?
try return simple value from you function, i mean
action':function () {
return true;
}
and when you call 'con' function you will be able to write
formdata_original = con();
In this case you can not worry about sinhronize
The second option is creation global object that belongs ot window or $. So try
window["formdata_original"] = false
and in your code inside confirm dialog
window["formdata_original"]=true.
I am creating a simple function that warns the user when they are about to close out of a web page. I am using the window.onbeforeonload function is javascript. What I am doing is that, I set a variable to false because of the evil window.onbeforeonload function.
function funky() {
var submitFormOkay = false;
window.onbeforeunload = function () {
if (submitFormOkay == false) {
return "You are about to leave this order form. You will lose any information...";
}
}
}
In my html, this is what I am doing
<input type="submit" id="submit_button" onclick="submitFormOkay = true;">
My question however is that I need a way to fire the function funky().
I know I could use an onclick but if I do what is going to set the value of submitFormOkay.
Any help would be appreciated.
Why not make submitFormOkay a parameter of the function funky, and just call it with the given parameter?
<input type="submit" id="submit_button" onclick="funky(true);">
And in the JS file:
function funky(submitFormOkay) {
window.onbeforeunload = function () {
if (submitFormOkay == false) {
return "You are about to leave this order form. You will lose any information...";
}
}
}
Without changing your HTML, I'd do this instead:
window.onbeforeunload = (function(w) {
w.submitFormOkay = false;
return function() {
if (!w.submitFormOkay) {
return "You are about to leave this order form. You will lose any information...";
}
};
})(window);
A problem with ngmiceli's solution is that window.onbeforeunload's callback never gets defined until the user is okay to leave the page.