setting the variable of js function from within htm - javascript

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.

Related

Clicking 'cancel' in confirm() method has the same result as clicking 'ok'

I am a beginner implementing a confirm method in my HTML code - when the user clicks on "x", they will be redirected to the home page. Otherwise, nothing happens.
My problem is that in confirm(), both "ok" and "cancel" options redirect to home page and I cannot figure out why.
I saw that many people have a similar problem, checked many forums and noticed that writing onclick="return confirmCancel() rather than onclick="confirmCancel()" helped in most of the cases but it did not solve the problem for me.
HTML:
<a onclick="return confirmCancel()"><img src="assets/cancel.svg"></a>
JS:
const confirmCancel = () => {
confirm("All your progress will be lost. Are you sure you want to leave?");
if (confirmCancel) {
window.location.assign("index.html");
} else {
return false;
}
}
You need to test the return value of confirm (rather than the truthiness of the confirmCancel function).
const confirmCancel = () => {
if (confirm("All your progress will be lost. Are you sure you want to leave?");) {
window.location.assign("index.html");
} else {
return false;
}
}
Try something like this.
<a onclick="pleaseConfirm"><img src="assets/cancel.svg"></a>
const pleaseConfirm = () => {
if (confirm("All your progress will be lost. Are you sure you want to leave?")) {
window.location.assign("index.html");
}
}
You're mostly there .. You need to check if confirm() is true .. Change:
confirm("All your progress will be lost. Are you sure you want to leave?");
if (confirmCancel)
To
var test_confirm = confirm("All your progress will be lost. Are you sure you want to leave?");
if (test_confirm === true)
Shorthand can be
if (confirm("All ... ... "){
You can do the functionality inside JavaScript instead of calling out JavaScript function in your HTML tag
<a id="btn-exit"><img src="assets/cancel.svg"></a>
var btnExit = document.querySelector('#btn-exit')
btnExit.addEventListener('click', () => {
if (confirm("are you sure?")) {
window.location.assign("index.html");
}
})

JavaScript and localStorage problems

Here is a quick example that should (but it doesn't work for some reason).
function clearSave()
{
var c = confirm("Are you sure you want to reset the current game?");
if (c==true)
{
localStorage.setItem("saved","false");
location.reload();
}
}
function save()
{
localStorage.setItem("saved","true");
setTimeout(save,1000);
}
function load()
{
if (localStorage.getItem("saved") == "true")
{
alert("Game Loaded");
}
else {
save();
}
}
When the page loads the load function is called. And when the user clicks a button to reset stuff the clearSave function is called.
But after the page is reloaded after the clearSave function is called the alert shows, meaning that the "saved" item is set to "true" somehow.
Any clues?
setTimeout(save,1000);
The above code is causing the error, you need to use some other strategy based on your needs
function save()
{
localStorage.setItem("saved","true");
//Below line needs to be updated
setTimeout(save,1000);
}

Multi Function Javascript Stop Other if Alert Cancel

I have a function executed onclick:
function delete_image() {
//alert;
var result = confirm('Are you sure you want to delete this item?');
if(result) { ....delete the image.... }
}
function new_image() { ....Do SOmething.... }
Then I call that by
<a onclick="setNewUploadOnDelete()">Delete</a>
I need if the "alert" of delete_image function is "cancel" then just stop the second function. I try below code but not work.
function setNewUploadOnDelete() {
var retvalue;
retvalue = delete_image();
if(retvalue == false) { return retvalue; }
return = new_image();
}
Is there any advice please?
setNewUploadOnDelete can be refactored to:
function setNewUploadOnDelete() {
return delete_image ? new_image() : false;
}
Here we're using Conditional Statements. This is simple enough that you may not need a function to do it.
On another note, it's generally not a good idea to use onclick to trigger JavaScript for reasons of performance and separation of concerns. Have a read into adding event listeners.

Can not prevent form submit when I add one line

I am stacked. My code can not prevent defaut action of submit. This was working fine until I add this.doSomething();.
Why this happens? Do I have to use preventDefault?
working code: http://jsfiddle.net/WwW5R/
HTML:
<div id="container">
<form action="" method="post" id="input">
<input type="submit">
</form>
</div>
JavaScript:
$(function() {
var ReserveUI = function($el) {
this.$form = {
input: $el.find('#input')
};
this._eventify();
};
ReserveUI.prototype.doSomething = function() {
return false;
}
ReserveUI.prototype._eventify = function() {
this.$form.input.submit(function() {
this.doSomething(); //if comment out this line, it works
return false;
});
};
var UI = new ReserveUI($("#container"));
});
thanks for reading:)
In your submit callback function, this no longer refers to your object, but to the element itself.
It's therefore causing an exception because the element has no doSomething property, and your return false is skipped.
Instead, write this:
ReserveUI.prototype._eventify = function() {
var self = this;
this.$form.input.submit(function(e) {
e.preventDefault(); // cancels event even if subsequent lines fail
self.doSomething();
});
};
See http://jsfiddle.net/xgGGx/1/ for a working example showing that it's just the scope issue causing the bug.
This is what script debugging tools are for - the reported error should have made the fault reasonably obvious...
This is a scope mismatch.
this.$form.input.submit(function() { //here "this" is ReserveUI
this.doSomething(); //here "this" is input button
return false;
});
And since there is no doSomething() on input button, the script breaks thus no longer executing the portion to return false.
Here is a way you can get around this
ReserveUI.prototype._eventify = function() {
var $this = this; //create a reference to the object
this.$form.input.submit(function() {
$this.doSomething(); //Now call the object method
return false;
});
};
Demo
Sounds like there's an error in your doSomething code (which I assume isn't just return false in your program).
To ensure the event does not continue, even if there's an error, do not return false but use e.preventDefault() instead:
this.$form.input.submit(function(e) {
e.preventDefault();
this.doSomething();
});

Javascript - Custom Confirm Dialog - replacing JS confirm

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

Categories