Disable onbeforeunload for submits [duplicate] - javascript

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.

Related

How to trigger submitting form automatically and use preventDefault

I have two ways of using form on a page.
First one is standard way when user types something in input field and clicks the submit button.
Second one is that the form is automatically filled and submitted depending on if a query string is passed to a page. (www.website.com/contact?fillform=true)
Everything works fine except I need yet to trigger the submit button for when query string is passed but currently it just refreshes the page.
I have done part in PHP, I have checked variables and they are ok.
Here is Codepen, e.preventDefault() is commented out since it doesn't work on window load
$(window).load(function() {
// Function for submitting form
function submitForm(e) {
console.log('I am in');
e.preventDefault();
jQuery.ajax({
... // Submit form
})
}
// Normal way of submitting form, works ok
$contactForm.on('submit', function(e) {
submitForm(e);
});
// This should trigger form automatically
if(fillFormAutomatically) {
// Everything so far works ok
// I just need to trigger form without page refresh but none of these works
$submitBtn.trigger('click');
$submitBtn.triggerHandler('click');
$contactForm.submit(e);
$contactForm.submit(function(e) {
console.log(e); // nothing in console shows here
submitForm(e);
});
submitForm(); // This triggers function but I can't pass event?
}
});
I think there is a couple of problems.
.load() was depreciated in jQuery 1.8, so don't use that. See: https://api.jquery.com/load-event/
Secondly, when you call submitForm() on window.ready(), there is no event. So you're trying to call .preventDefault() on undefined. Just move it to the .submit() function.
Does that answer your question?
$(window).ready(function() {
var $form = $("#form");
var $submitBtn = $("#submitBtn");
// Send form on window load
submitForm();
// Normal way
$form.submit(function(e) {
e.preventDefault();
submitForm(e);
});
// Send form
function submitForm() {
$('#vardump').append('Sending form...');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="form">
<input type="text" value="Somedata">
<button id="submitBtn">Submit</button>
</form>
<div id="vardump"></div>

Javascript onSubmit not returning false

I'm having an issue with my onsubmit code. I'm using a calculator from a third party company and I am trying to trigger some javascript when the form is submitted. The alert will fire off but if I have the return set to false the form still submits.
Here is the line of code I am working with in my own environment:
document.getElementsByTagName("Form")[3].onsubmit = function () { alert('Test'); return false; };
I have built a replica here:
(For what ever reason it wont load in the snippet, I copied the same code to my server and it works fine, so here is it in action. Page)
function myFunction() {
document.getElementsByTagName("Form")[0].onsubmit = function () { alert('Test'); return false; };
}
<button onclick="myFunction()">Wait for script to load then press this button to add the onsubmit, then you can press calculate</button>
<script src="https://calculators.symmetry.com/widget/js/salary.js?key=RHA0Slc2ZjEydjNkR0Y2eTEvOUxpZz09"></script>
I haven't figured out how to do an onload detection for a script yet so that's why you have to wait for the script to load then press the button to insert the javascript.
Thanks for any help.
Well.. in your solution you are adding a new event handler to the form on every button click
Instead of declaring the event handler on page load and then trigger it
It should be....
<script>
function onMyPageLoaded()
{
document.getElementsByTagName("Form")[0].onsubmit = function (e)
{
e.preventDefault();
// place your code here
return false; // cancel form submit
};
}
function doSomething() // use this ONLY if you intend to by-pass the native submit mechanism
{
document.getElementsByTagName("Form")[0].submit(); // trigger the event here
}
</script>
<body onload="onMyPageLoaded()">
<form>
<button type="submit">send</button>
</form>
</body>

Javascript or jQuery popup when user click links other than Submit button

I have created a form where user can create his profile, now I want that if user do not click on save/submit button on the page and clicks on any other available link other than save.
Then he should get confirm popup of JavaScript mentioning that you are aborting the creation of profile. I am unable to find any event via which I can achieve this.
Other links are navigation links available on my page.
If you are using button for submit and others as a link then you can find out like this:
$(document).ready(function() {
$(document).('on','click',function(){
var pressedButton = $(this).text();
if(pressedButon == "Submit" || pressedButton =="Save")
{
return false;
}
else
{
$("a").on('click',function() {
var confirmAns = confirm('Your message');
if(confirmAns == true)
{
// DO whatever you want...
}
else
{
//Do whatever you want...
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use onblur event for it and you can achieve your goal. So when a user click anywhere in your web page then the onblur event automatically fire.
You should use onblur event on your save/submit button.
<button onblur="myFunction()" type="button">Save</button>
<script>
function myFunction() {
var txt;
var r = confirm("You are aborting the creation of profile");
if (r == true) {
return true;
} else {
return false;
}
}
</script>
Try using some plugin. There is one jQuery plugin "Are You Sure"
So you just need below code snippet
$('form').areYouSure();
// OR
$('form.my_form_class').areYouSure();
There are some advanced option available with plugin. Checkout its documentation.
If I understood right, you want this two possibilities:
1.User clicks submit button: form gets submitted
2.User clicks "a" link: get alert asking for confirmation to leave the registration process.
First point will be done automatically as it's a form submit button without the need of extra jQuery.
Second point would just need the following code in order to show the confirmation button:
<script>
$(document).ready(function(){
$('a').on('click',function(e){
if (!confirm("Are you sure you want to exit the registration process?")){
e.preventDefault();
return false;
}
});
});
</script>

Javascript return false; is not cancelling a form submit for another .submit jQuery call

I have this jQuery function injected on every page in order to disable submit buttons after they are clicked.
$('form').submit(function () {
var btn = $('input[type=submit]', this);
disableButtonOrLink.disableSubmit(btn);
btn = $('button[type=submit]', this);
disableButtonOrLink.disableSubmit(btn);
});
The problem is that I also have some backend validation that is sometimes attached to the form in the the shape of something like this
<form action="someAction" method="post" name="someForm" class="form"
onsubmit="var invalid=false;
invalid=someAction();
if(invalid){return false;}"
id="someForm">
The issue I am having that is occurs is that the ('form').submit action is always being called after the return false. The form isn't actually being submitted due to the return false; however this jQuery function is still being called after. Is there anyway to prevent this .submit from being called?
Just to clarify exactly what is happening:
The onSubmit on the form is being called;
The return false section is being hit and properly canceling the submit;
The ('form').submit is still being called after the onSubmit completes as if the form's submit wasn't canceled and is disabling buttons.
I would like to prevent the last step from occurring.
You can use JQuery to find those buttons inside form and use a method from preventing stuff that they normally do.
Example:
$("form button").on('click', function(e){
e.preventDefault();
});
I would probably try something like this
$('#someForm').on('submit', function(e) {
if ($(this).data('some-action')) {
e.preventDefault();
return false;
}
//... then disable buttons, etc
});
In this case you need to add the attribute data-some-action to the form, evaluated with whatever backend validation you are doing.
UPDATE
$('#someForm').on('submit', function(e) {
if ($(this).data('some-action') == 'error-message') {
e.preventDefault();
alert('error!');
return false;
}
if ($(this).data('some-action') == 'reload') {
e.preventDefault();
document.location.reload(true);
}
//... then disable buttons, etc
});

Preventing multiple clicks on button

I have following jQuery code to prevent double clicking a button. It works fine. I am using Page_ClientValidate() to ensure that the double click is prevented only if the page is valid. [If there are validation errors the flag should not be set as there is no postback to server started]
Is there a better method to prevent the second click on the button before the page loads back?
Can we set the flag isOperationInProgress = yesIndicator only if the page is causing a postback to server? Is there a suitable event for it that will be called before the user can click on the button for the second time?
Note: I am looking for a solution that won't require any new API
Note: This question is not a duplicate. Here I am trying to avoid the use of Page_ClientValidate(). Also I am looking for an event where I can move the code so that I need not use Page_ClientValidate()
Note: No ajax involved in my scenario. The ASP.Net form will be submitted to server synchronously. The button click event in javascript is only for preventing double click. The form submission is synchronous using ASP.Net.
Present Code
$(document).ready(function () {
var noIndicator = 'No';
var yesIndicator = 'Yes';
var isOperationInProgress = 'No';
$('.applicationButton').click(function (e) {
// Prevent button from double click
var isPageValid = Page_ClientValidate();
if (isPageValid) {
if (isOperationInProgress == noIndicator) {
isOperationInProgress = yesIndicator;
} else {
e.preventDefault();
}
}
});
});
References:
Validator causes improper behavior for double click check
Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)
Note by #Peter Ivan in the above references:
calling Page_ClientValidate() repeatedly may cause the page to be too obtrusive (multiple alerts etc.).
I found this solution that is simple and worked for me:
<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>
This solution was found in:
Original solution
JS provides an easy solution by using the event properties:
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){//activate on first click only to avoid hiding again on multiple clicks
// code here. // It will execute only once on multiple clicks
}
});
disable the button on click, enable it after the operation completes
$(document).ready(function () {
$("#btn").on("click", function() {
$(this).attr("disabled", "disabled");
doWork(); //this method contains your logic
});
});
function doWork() {
alert("doing work");
//actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
//I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
setTimeout('$("#btn").removeAttr("disabled")', 1500);
}
working example
I modified the solution by #Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
After hours of searching i fixed it in this way:
old_timestamp = null;
$('#productivity_table').on('click', function(event) {
// code executed at first load
// not working if you press too many clicks, it waits 1 second
if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
{
// write the code / slide / fade / whatever
old_timestamp = event.timeStamp;
}
});
you can use jQuery's [one][1] :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using count,
clickcount++;
if (clickcount == 1) {}
After coming back again clickcount set to zero.
May be this will help and give the desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
<p>Hello</p>
We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.
$(document).ready(function () {
$("#disable").on('click', function () {
$(this).off('click');
// enter code here
});
})
This should work for you:
$(document).ready(function () {
$('.applicationButton').click(function (e) {
var btn = $(this),
isPageValid = Page_ClientValidate(); // cache state of page validation
if (!isPageValid) {
// page isn't valid, block form submission
e.preventDefault();
}
// disable the button only if the page is valid.
// when the postback returns, the button will be re-enabled by default
btn.prop('disabled', isPageValid);
return isPageValid;
});
});
Please note that you should also take steps server-side to prevent double-posts as not every visitor to your site will be polite enough to visit it with a browser (let alone a JavaScript-enabled browser).
The absolute best way I've found is to immediately disable the button when clicked:
$('#myButton').click(function() {
$('#myButton').prop('disabled', true);
});
And re-enable it when needed, for example:
validation failed
error while processing the form data by the server, then after an error response using jQuery
Another way to avoid a quick double-click is to use the native JavaScript function ondblclick, but in this case it doesn't work if the submit form works through jQuery.
One way you do this is set a counter and if number exceeds the certain number return false.
easy as this.
var mybutton_counter=0;
$("#mybutton").on('click', function(e){
if (mybutton_counter>0){return false;} //you can set the number to any
//your call
mybutton_counter++; //incremental
});
make sure, if statement is on top of your call.
If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.
First set add a style to your button:
<h:commandButton id="SaveBtn" value="Save"
styleClass="hideOnClick"
actionListener="#{someBean.saveAction()}"/>
Then make it hide when clicked.
$(document).ready(function() {
$(".hideOnClick").click(function(e) {
$(e.toElement).hide();
});
});
Just copy paste this code in your script and edit #button1 with your button id and it will resolve your issue.
<script type="text/javascript">
$(document).ready(function(){
$("#button1").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script
Plain JavaScript:
Set an attribute to the element being interacted
Remove the attribute after a timeout
If the element has the attribute, do nothing
const throttleInput = document.querySelector('button');
throttleInput.onclick = function() {
if (!throttleInput.hasAttribute('data-prevent-double-click')) {
throttleInput.setAttribute('data-prevent-double-click', true);
throttleInput.setAttribute('disabled', true);
document.body.append("Foo!");
}
setTimeout(function() {
throttleInput.removeAttribute('disabled');
throttleInput.removeAttribute('data-prevent-double-click');
}, 3000);
}
<button>Click to add "Foo"!</button>
We also set the button to .disabled=true. I added the HTML Command input with type hidden to identify if the transaction has been added by the Computer Server to the Database.
Example HTML and PHP Commands:
<button onclick="myAddFunction(<?php echo $value['patient_id'];?>)" id="addButtonId">ADD</button>
<input type="hidden" id="hasPatientInListParam" value="<?php echo $hasPatientInListParamValue;?>">
Example Javascript Command:
function myAddFunction(patientId) {
document.getElementById("addButtonId").disabled=true;
var hasPatientInList = document.getElementById("hasPatientInListParam").value;
if (hasPatientInList) {
alert("Only one (1) patient in each List.");
return;
}
window.location.href = "webAddress/addTransaction/"+patientId; //reloads page
}
After reloading the page, the computer auto-sets the button to .disabled=false. At present, these actions prevent the multiple clicks problem in our case.
I hope these help you too.
Thank you.
One way I found that works is using bootstrap css to display a modal window with a spinner on it. This way nothing in the background can be clicked. Just need to make sure that you hide the modal window again after your long process completes.
so I found a simple solution, hope this helps.
all I had to do was create a counter = 0, and make the function that runs when clicked only runnable if the counter is = 0, when someone clicks the function the first line in the function sets counter = 1 and this will prevent the user from running the function multiple times when the function is done the last line of the code inside the function sets counter to 0 again
you could use a structure like this, it will execute just once:
document.getElementById('buttonID').addEventListener('click', () => {
...Do things...
},{once:true});

Categories

Resources