Disable window beforeunload property for one button - javascript

I have disabled page redirects/reloads with window.beforeunload function, but once the form submission happens in the page, I want to redirect to the next page, without showing the window.beforeunload alerts. How can I do that?
$(window).on("beforeunload", function () {
return "Changes won't be saved.";
});
This is the button that shouldn't trigger the alert:
<form id="command" action="/some-uri" method="post">
<button type="submit" value="NEXT" class="btn btn-red- light">NEXT</button>
</form>

Check a variable
pseudo code
if some dirty change -> window.hasSomeDirtyChanges = true;
if all dirty changes saved -> window.hasSomeDirtyChanges = false;
$(window).on("beforeunload", function () {
if(!window.hasSomeDirtyChanges) return true;
return "Changes won't be saved.";
});
So this way you don't have to bind unbind every time you go to a page. This will work for all the pages, you just need to manage a variable.

add a class to every element that you don't want to trigger the event, for example ".not-trigger", then:
$(".not-trigger").on("click", function(){
$(window).off("beforeonunload");
});

Related

Submitting POST Request only once [duplicate]

I have a submit button at the end of the form.
I have added the following condition to the submit button:
onClick="this.disabled=true;
this.value='Sending…';
this.form.submit();"
But when it moves to the next page, the parameters did not pass and null values are passed.
You should first submit your form and then change the value of your submit:
onClick="this.form.submit(); this.disabled=true; this.value='Sending…'; "
Probably you're submitting the form twice.
Remove the this.form.submit() or add return false at the end.
you should end up with onClick="this.disabled=true; this.value='Sending…';"
tested on IE11, FF53, GC58 :
onclick="var e=this;setTimeout(function(){e.disabled=true;},0);return true;"
You need to disable the button in the onsubmit event of the <form>:
<form action='/' method='POST' onsubmit='disableButton()'>
<input name='txt' type='text' required />
<button id='btn' type='submit'>Post</button>
</form>
<script>
function disableButton() {
var btn = document.getElementById('btn');
btn.disabled = true;
btn.innerText = 'Posting...'
}
</script>
Note: this way if you have a form element which has the required attribute will work.
Disabled HTML forms elements aren't sent along with the post/get values when you submit the form. So if you disable your submit button once clicked and that this submit button have the name attribute set, It will not be sent in the post/get values since the element is now disabled. This is normal behavior.
One of the way to overcome this problem is using hidden form elements.
the trick is to delayed the button to be disabled, and submit the form you can use
window.setTimeout('this.disabled=true',0);
yes even with 0 MS is working
Using JQuery, you can do this..
$("#submitbutton").click(
function() {
alert("Sending...");
window.location.replace("path to url");
}
);
If you disable the button, then its name=value pair will indeed not be sent as parameter. But the remnant of the parameters should be sent (as long as their respective input elements and the parent form are not disabled). Likely you're testing the button only or the other input fields or even the form are disabled?
Here's a drop-in example that expands on Andreas Köberle's solution. It uses jQuery for the event handler and the document ready event, but those could be switched to plain JS:
(function(document, $) {
$(function() {
$(document).on('click', '[disable-on-click], .disable-on-click', function() {
var disableText = this.getAttribute("data-disable-text") || 'Processing...';
if(this.form) {
this.form.submit();
}
this.disabled = true;
if(this.tagName === 'BUTTON') {
this.innerHTML = disableText;
} else if(this.tagName === 'INPUT') {
this.value = disableText;
}
});
});
})(document, jQuery);
It can then be used in HTML like this:
<button disable-on-click data-disable-text="Saving...">Click Me</button>
<button class="disable-on-click">Click Me</button>
<input type="submit" disable-on-click value="Click Me" />
I don't think you need this.form.submit(). The disabling code should run, then it will pass on the click which will click the form.
Another solution i´ve used is to move the button instead of disabling it. In that case you don´t have those "disable" problems.
Finally what you really want is people not to press twice, if the button is not there they can´t do it.
You may also replace it with another button.
function xxxx() {
// submit or validate here , disable after that using below
document.getElementById('buttonId').disabled = 'disabled';
document.getElementById('buttonId').disabled = '';
}
Your question is confusing and you really should post some code, but this should work:
onClick="this.disabled=true; this.value='Sending...'; submitForm(); return false;"
I think that when you use this.form.submit() it's doing what happens naturally when you click the submit button. If you want same-page submit, you should look into using AJAX in the submitForm() method (above).
Also, returning false at the end of the onClick attribute value suppresses the default event from firing (in this case submitting the form).
A better trick, so you don't lose the value of the button is
function showwait() {
document.getElementById('WAIT').style['display']='inline';
document.getElementById('BUTTONS').style['display']='none';
}
wrap code to show in a div
id=WAIT style="display:none"> text to display (end div)
wrap code to hide in a div
id=BUTTONS style="display:inline"> ... buttons or whatever to hide with
onclick="showwait();"
(end div)
In my case this was needed.
Disable submit button on form submit
It works fine in Internet Explorer and Firefox without it, but it did not work in Google Chrome.
The problem is that you are disabling the button before it can actually trigger the submit event.
I think easy way to disable button is :data => { disable_with: "Saving.." }
This will submit a form and then make a button disable, Also it won't disable button if you have any validations like required = 'required'.
In this working example, the user confirms in JavaScript that he really wants to abort. If true, the button is disabled to prevent double click and then the code behind which updates the database will run.
<asp:button id="btnAbort" runat="server" OnClick="btnAbort_Click" OnClientClick="if (!abort()) {return false;};" UseSubmitBehavior="false" text="Abort" ></asp:button>
I had issues because .net can change the name of the button
function abort() {
if (confirm('<asp:Literal runat="server" Text="Do you want to abort?" />')) {
var btn = document.getElementById('btnAbort');
btn.disabled = true;
btn.innerText = 'Aborting...'
return true;
}
else {
return false;
}
}
Because you are overriding the OnClick with OnClientClick, even if your validation method succeeds, the code behind wont work. That's why you set UseSubmitBehavior to false to make it work
PS: You don't need the OnClick if your code is in vb.net!
Okay, i did a lot of research on how to make this work perfectly.
So the best option is to create a set timeout for disabling a button onclick.
Now, the problem arise when there is a submit function running on the backend. Then the events become stacked in a queue and whenever the javascript "button.disabled == true"is added to the onclick event, only the first action(i.e. disabling the button) gets triggered and not the submit action which is running in the backend(This backend submit function can comprise of anything such as $.ajax).
For disabling Single button on click :
function() { //i always create annonymous function to avoid polluting global
space
var btn = document.getElementsByClassName("btn");
btn.onclick = function() {
setTimeout(function() {
backButton.disabled = true;
}, 0);
};
}
}();
This code will disable your button and also would run the function on the queue. timeout = 0 actually is used for firing subsequent backend tasks.
For disabling all btns in the screen :
(function() {
let i, element, list, o;
element = document.getElementsByClassName("classx");
if (element) {
element = element[0];
list = element.getElementsByTagName("button");
for (i = 0; i < list.length; i++) {
o = list[i];
o.onclick = function() {
setTimeout(function() {
let i;
for (i = 0; i < list.length; i++) {
list[i].disabled = true;
}
}, 0);
return true;
}
}
}
})();
This would help you disable all of the buttons present in the page. (Just use it according to your usecase.)
Also, this(disabled button) is a good use case for settimeout=0, functionality description as it will "defer" the call until the currently "stacked javascript events" are finished.
Thank you and hope this helps someone's in the future.
I did the trick. When set timeout, it works perfectly and sending all values.
$(document).ready(function () {
document.getElementById('btnSendMail').onclick = function () {
setTimeout(function () {
document.getElementById('btnSendMail').value = 'Sending…';
document.getElementById('btnSendMail').disabled = true;
}, 850);
}
});

Javascript Confirm Dialog Not Activiting

Here is code:
<form method="post" id="cp_ind_form">
// lots of input fields!
<input type="submit" name="update_submit" value="Update" />
<input type="submit" name="delete_submit" value="Delete" onclick="deleteConfirm()" />
</form>
scripts.js (confirmed that this file is connected to above page)
(function deleteConfirm() {
var s = document.getElementById('confirm');
s.onchange = function() {
var yes = confirm('Do you really want to delete this location?');
if (yes) {
var f = document.getElementById('cp_ind_form');
f.submit();
}
}
})();
}
This is driving me insane. Such a basic function is not working here? I am basically copying it from other code that I have that DOES work, and this is no different. Can someone confirm if I am missing a small detail?
Look at the code.
You are adding an onchange event to something when you click the submit.
You are not triggering the confirm to be shown, and you are not cancelling the original submission.
AND it makes no sense to have it wrapped with (funciton(){})();
It should be
function deleteConfirm() {
return confirm('Do you really want to delete this location?');
}
and
onclick="return deleteConfirm();"
To actually execute the confirm when deleteConfirm is called, change your code to this:
function deleteConfirm() {
var yes = confirm('Do you really want to delete this location?');
if (yes) {
document.getElementById('cp_ind_form').submit();
}
// block default submit
return(false);
}
This also returns false so that the default form submission doesn't happen.
Then, change your HTML to this:
onsubmit="return deleteConfirm()"
If you handle the onsubmit instead of onclick, you can block the default submit by returning false from the handler.
deleteConfirm() is run on button click. Inside this function you are assigning code to the eventonchange which than waits for the item #confirm to be changed. I don't know where is that element but I pressume the event is never fired so the confirm box never shows

How to disable beforeunload action when user is submitting a form?

I have this little piece of code:
<script>
$(window).bind('beforeunload', function() {
$.ajax({
async: false,
type: 'POST',
url: '/something'
});
});
</script>
I wonder, how could I disable this request when user hits the submit button.
Basically something like here, on SO. When your asking a question and decide to close the page, you get a warning window, but that doesn't happen when you're submitting the form.
Call unbind using the beforeunload event handler:
$('form#someForm').submit(function() {
$(window).unbind('beforeunload');
});
To prevent the form from being submitted, add the following line:
return false;
Use
$('form').submit(function () {
window.onbeforeunload = null;
});
Make sure you have this before you main submit function! (if any)
This is what we use:
On the document ready we call the beforeunload function.
$(document).ready(function(){
$(window).bind("beforeunload", function(){ return(false); });
});
Before any submit or location.reload we unbind the variable.
$(window).unbind('beforeunload');
formXXX.submit();
$(window).unbind("beforeunload");
location.reload(true);
Looking for Detect onbeforeunload for ASP.NET web application well I was,
I've to show warning message if some input control changes on the page using ASP.NET with Master Page and Content Pages. I'm using 3 content placeholders on the master page and the last one is after the form
<form runat="server" id="myForm">
so after the form closing tag and before the body closing tag used this script
<script>
var warnMessage = "Save your unsaved changes before leaving this page!";
$("input").change(function () {
window.onbeforeunload = function () {
return 'You have unsaved changes on this page!';
}
});
$("select").change(function () {
window.onbeforeunload = function () {
return 'You have unsaved changes on this page!';
}
});
$(function () {
$('button[type=submit]').click(function (e) {
window.onbeforeunload = null;
});
});
</script>
beforeunload doesn't work reliably this way, as far as binding goes. You should assign it natively
so I got it working like this bind and unbind didn't work out for me also With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.dirtyforms/2.0.0-beta00006/jquery.dirtyforms.min.js"></script>
<script type="text/javascript">
$(function() {
$('#form_verify').dirtyForms();
})
</script>
<title></title>
<body>
<form id="form_verify" action="a.php" method="POST">
Firt Name <input type="text">
Last Name <input type="file">
<input type="submit">
</form>
if you're using bind then use this:
$('form').submit(function () {
$(window).unbind('beforeunload');
});
This will be good for all form submit.
Super old question but might be useful to others.
Simply detaching the "beforeunload" from the "submit" event would not work for me - because the submit handler was being called even when there were errors in the form that the user had to fix. So if a user attempted to submit the form, then received the errors, then clicked to another page, they would be able to leave without the warning.
Here's my workaround that seems to work pretty well.
(function($) {
var attached = false,
allowed = false;
// catch any input field change events bubbling up from the form
$("form").on("change", function () {
// attach the listener once
if (!attached) {
$("body").on("click", function (e) {
// check that the click came from inside the form
// if it did - set flag to allow leaving the page
// otherwise - hit them with the warning
allowed = $(e.target).parents("form").length != 0;
});
window.addEventListener('beforeunload', function (event) {
// only allow if submit was called
if (!allowed) {
event.preventDefault();
event.returnValue = 'You have unsaved changes.';
}
});
}
attached = true;
});
}(jQuery));
This way, if the click to leave the page originated from inside the form (like the submit button) - it will not display the warning. If the click to leave the page originated from outside of the form, then it will warn the user.

How to disable submit button once it has been clicked?

I have a submit button at the end of the form.
I have added the following condition to the submit button:
onClick="this.disabled=true;
this.value='Sending…';
this.form.submit();"
But when it moves to the next page, the parameters did not pass and null values are passed.
You should first submit your form and then change the value of your submit:
onClick="this.form.submit(); this.disabled=true; this.value='Sending…'; "
Probably you're submitting the form twice.
Remove the this.form.submit() or add return false at the end.
you should end up with onClick="this.disabled=true; this.value='Sending…';"
tested on IE11, FF53, GC58 :
onclick="var e=this;setTimeout(function(){e.disabled=true;},0);return true;"
You need to disable the button in the onsubmit event of the <form>:
<form action='/' method='POST' onsubmit='disableButton()'>
<input name='txt' type='text' required />
<button id='btn' type='submit'>Post</button>
</form>
<script>
function disableButton() {
var btn = document.getElementById('btn');
btn.disabled = true;
btn.innerText = 'Posting...'
}
</script>
Note: this way if you have a form element which has the required attribute will work.
Disabled HTML forms elements aren't sent along with the post/get values when you submit the form. So if you disable your submit button once clicked and that this submit button have the name attribute set, It will not be sent in the post/get values since the element is now disabled. This is normal behavior.
One of the way to overcome this problem is using hidden form elements.
the trick is to delayed the button to be disabled, and submit the form you can use
window.setTimeout('this.disabled=true',0);
yes even with 0 MS is working
Using JQuery, you can do this..
$("#submitbutton").click(
function() {
alert("Sending...");
window.location.replace("path to url");
}
);
If you disable the button, then its name=value pair will indeed not be sent as parameter. But the remnant of the parameters should be sent (as long as their respective input elements and the parent form are not disabled). Likely you're testing the button only or the other input fields or even the form are disabled?
Here's a drop-in example that expands on Andreas Köberle's solution. It uses jQuery for the event handler and the document ready event, but those could be switched to plain JS:
(function(document, $) {
$(function() {
$(document).on('click', '[disable-on-click], .disable-on-click', function() {
var disableText = this.getAttribute("data-disable-text") || 'Processing...';
if(this.form) {
this.form.submit();
}
this.disabled = true;
if(this.tagName === 'BUTTON') {
this.innerHTML = disableText;
} else if(this.tagName === 'INPUT') {
this.value = disableText;
}
});
});
})(document, jQuery);
It can then be used in HTML like this:
<button disable-on-click data-disable-text="Saving...">Click Me</button>
<button class="disable-on-click">Click Me</button>
<input type="submit" disable-on-click value="Click Me" />
I don't think you need this.form.submit(). The disabling code should run, then it will pass on the click which will click the form.
Another solution i´ve used is to move the button instead of disabling it. In that case you don´t have those "disable" problems.
Finally what you really want is people not to press twice, if the button is not there they can´t do it.
You may also replace it with another button.
function xxxx() {
// submit or validate here , disable after that using below
document.getElementById('buttonId').disabled = 'disabled';
document.getElementById('buttonId').disabled = '';
}
Your question is confusing and you really should post some code, but this should work:
onClick="this.disabled=true; this.value='Sending...'; submitForm(); return false;"
I think that when you use this.form.submit() it's doing what happens naturally when you click the submit button. If you want same-page submit, you should look into using AJAX in the submitForm() method (above).
Also, returning false at the end of the onClick attribute value suppresses the default event from firing (in this case submitting the form).
A better trick, so you don't lose the value of the button is
function showwait() {
document.getElementById('WAIT').style['display']='inline';
document.getElementById('BUTTONS').style['display']='none';
}
wrap code to show in a div
id=WAIT style="display:none"> text to display (end div)
wrap code to hide in a div
id=BUTTONS style="display:inline"> ... buttons or whatever to hide with
onclick="showwait();"
(end div)
In my case this was needed.
Disable submit button on form submit
It works fine in Internet Explorer and Firefox without it, but it did not work in Google Chrome.
The problem is that you are disabling the button before it can actually trigger the submit event.
I think easy way to disable button is :data => { disable_with: "Saving.." }
This will submit a form and then make a button disable, Also it won't disable button if you have any validations like required = 'required'.
In this working example, the user confirms in JavaScript that he really wants to abort. If true, the button is disabled to prevent double click and then the code behind which updates the database will run.
<asp:button id="btnAbort" runat="server" OnClick="btnAbort_Click" OnClientClick="if (!abort()) {return false;};" UseSubmitBehavior="false" text="Abort" ></asp:button>
I had issues because .net can change the name of the button
function abort() {
if (confirm('<asp:Literal runat="server" Text="Do you want to abort?" />')) {
var btn = document.getElementById('btnAbort');
btn.disabled = true;
btn.innerText = 'Aborting...'
return true;
}
else {
return false;
}
}
Because you are overriding the OnClick with OnClientClick, even if your validation method succeeds, the code behind wont work. That's why you set UseSubmitBehavior to false to make it work
PS: You don't need the OnClick if your code is in vb.net!
Okay, i did a lot of research on how to make this work perfectly.
So the best option is to create a set timeout for disabling a button onclick.
Now, the problem arise when there is a submit function running on the backend. Then the events become stacked in a queue and whenever the javascript "button.disabled == true"is added to the onclick event, only the first action(i.e. disabling the button) gets triggered and not the submit action which is running in the backend(This backend submit function can comprise of anything such as $.ajax).
For disabling Single button on click :
function() { //i always create annonymous function to avoid polluting global
space
var btn = document.getElementsByClassName("btn");
btn.onclick = function() {
setTimeout(function() {
backButton.disabled = true;
}, 0);
};
}
}();
This code will disable your button and also would run the function on the queue. timeout = 0 actually is used for firing subsequent backend tasks.
For disabling all btns in the screen :
(function() {
let i, element, list, o;
element = document.getElementsByClassName("classx");
if (element) {
element = element[0];
list = element.getElementsByTagName("button");
for (i = 0; i < list.length; i++) {
o = list[i];
o.onclick = function() {
setTimeout(function() {
let i;
for (i = 0; i < list.length; i++) {
list[i].disabled = true;
}
}, 0);
return true;
}
}
}
})();
This would help you disable all of the buttons present in the page. (Just use it according to your usecase.)
Also, this(disabled button) is a good use case for settimeout=0, functionality description as it will "defer" the call until the currently "stacked javascript events" are finished.
Thank you and hope this helps someone's in the future.
I did the trick. When set timeout, it works perfectly and sending all values.
$(document).ready(function () {
document.getElementById('btnSendMail').onclick = function () {
setTimeout(function () {
document.getElementById('btnSendMail').value = 'Sending…';
document.getElementById('btnSendMail').disabled = true;
}, 850);
}
});

How to avoid a postback in JavaScript?

I have an ASP.NET page which has a button it it. The button click launches a modal dialog box using JavaScript. Based on the value returned by the modal dialog box, I want to proceed with, or cancel the post back that happens. How do I do this?
Adding "return false;" to the onclick attribute of the button will prevent the automatic postback.
Is this what you are trying to do?
<input type="button" id="myButton" value="Click!" />
<script type="text/javascript">
document.getElementById('myButton').onclick = function() {
var agree = confirm('Are you sure?');
if (!agree) return false;
};
</script>
function HandleClick()
{
// do some work;
if (some condition) return true; //proceed
else return false; //cancel;
}
set the OnClientClick attribute to "return HandleClick()"
Basically what Wayne said, but you just need to put 'return false;' in the function that presents the modal. If it's the value you want, let the postback happen. If not, have the function return false and it will stop the submit.

Categories