Prevent beforeunload function from executing if submit button is clicked - javascript

I have the following function that gives a warning to the user if they are exiting the page when the $('.article_div textarea') form field is populated.
$(window).on('beforeunload', function(event) {
var unsaved = "Are you sure you want to exit?";
var text = $('.article_div textarea').val();
if (text.length > 0){
return unsaved;
}
});
However, I would like to prevent this popup from executing when they click the submit button to the actual form.
How can I ammend the function to account for this? The element of the submit button is
$('button.submit_post').

You can create a boolean which gets positive when you click on submit Or remove the event of unload when clicked. The code will be as follows:
var isSubmitClicked = false;
$('button .submit_post').on("click",onClick);
function onClick(e){
isSubmitClicked = true;
}
$(window).on('beforeunload', function(event) {
if(isSubmitClicked){
isSubmitClicked = false;
return;
}
// Rest of your method.
}

How about binding a event handler to the submit event instead of the submit button element?
Maybe like this:
var submitted = false;
$('form').on("submit", function() {
submitted = true;
console.log('submitted');
});
$(window).on('beforeunload', function(event) {
if(submitted){
submitted = false;
console.log('aborted because of submit');
return;
}
console.log('rest of code');
// Rest of your method.
});

Related

How to avoid triggering false function between change and click

I have an input and a clear button. If the user type something in the input field and blur it, change() will be trigger and do something. But if I want to click clear button and trigger click(), change() will still be triggered. How do I solve this?
I tried this, but it doesn't work. var clear will never be true.
$("#inputid").change(function() {
var clear = false;
$("#clearbtn").click(function() {
// if clear button is clicked, do something
clear = true;
});
if (clear) {
return;
}
// if clear button is not clicked, do something else
...
this is quite tricky
the problem is onchange event is called before the clear button click event is called
to overcome this you can introduce a timer in the onchange event so that it waits for user's immediate action
like this:
$(document).ready(function(){
var clear = false;
var isTimerOn = false;
function HandleChange(){
if(clear){
// if clear button is clicked, do something
$("#inputid").val("");
}else{
// if clear button is not clicked, do something else
alert("do something else");
}
clear = false;
isTimerOn = false;
}
$("#inputid").change(function() {
isTimerOn = true;
setTimeout(HandleChange, 80);
});
$("#clearbtn").click(function() {
clear = true;
if(!isTimerOn){
HandleChange();
}
});
});
here's fiddle: https://jsfiddle.net/6d9r1qsc/
You should move the click event outside of the change event.
$("#clearbtn").click(function() {
// if clear button is clicked, do something
$("#inputid").val("");
});

event.prevendefault() not working inside a function that has an each() function

I have function that will do a simple validation, if every input text is empyt an alert will pop up, and the program will stop. Function will fire up after a click of a button. I'm allready passing the event, but somehow the event.PreventDefault() not working, so still accessing the server side code.
Below is the function to do simple validation.
var checkRequired = function(event)
$('.box-load .requir').each(function(index,item) {
var index = $(item).data('index');
if(index === 'text') {
if ($(item).val() == "") {
$(this).focus();
alert('Please input the required parameter');
event.preventDefault();
}
}
});
}
For the trigger the function I use this code:
$(document).on('click','.box-load .btn-save', function(event) {
event.preventDefault();
checkRequired(event);
Bellow the checkRequired(), I'm gonna do an ajax request. What i want is, if one of the input text is empty, the event is stop. But with that code, is not working. Any suggestion?
Thanks in advance.
if you call event.preventDefault(), default action of the event will not be triggered.
$(document).on('click','.box-load .btn-save', function(event)
{
checkRequired(event);
event.preventDefault();
event.preventDefault() should be outside the for loop.
var checkRequired = function(event)
{
$('.box-load .requir').each(function(index,item) {
var index = $(item).data('index');
if(index === 'text') {
if ($(item).val() == "") {
$(this).focus();
alert('Please input the required parameter');
}
}
});
event.preventDefault();
}
event.preventDefault() will just stop the default action, not stop your function call. If you don't specifically return from your function, it will go on and launch the ajax.

Capture browser close event

I want to capture browser close event using javascript. I googled but I am not getting any solution anywhere,below is my code where I have handled anchor, Form Submit and Submit button on onbeforeunload.
<script>
var validNavigation = false;
function wireUpEvents() {
window.onbeforeunload = function() {
if (!validNavigation) {
// invalidate session
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keydown', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
Is there any way I can capture browser close button event, I have seen developers using X and Y axis but that is not recommended most of developers.
Thanks..
You can try this .. prompting user to confirm before closing tab. and you can do some thing you need
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>

Submit form from a button tag

I added an event listener when my form is submitted, this is the code:
var formo = document.getElementById("ing");
formo.addEventListener("submit", validation, false);
but I'm submitting the form with a button tag with this code:
var enviar = document.getElementById("submit_btn");
enviar.addEventListener("click", envioFormulario, false);
function envioFormulario() {
this.disabled = true;
this.value = "Sending";
this.form.submit();
}
with this the form is submitted but the submit event (the first lines of code) doesn't seems to work what can I do to make it work?
I agree with #Mathletics comment. Just do the validation when you click, and submit if it passes validation:
var enviar = document.getElementById("submit_btn");
enviar.addEventListener("click", envioFormulario, false);
function envioFormulario() {
if (validation()) {
this.disabled = true;
this.value = "Sending";
this.form.submit();
} else {
alert("Validation failed. Didn't submit");
}
}
Try setting the function name in the "onsubmit" attribute of your form element.
Your issue may be around preventing the default behaviour from occuring.
You need to receive the event in your handler function to do that.
function validation( event )
{
if ( event.preventDefault ) event.preventDefault();
event.returnValue = false;
// continue validating
}

Activating OnBeforeUnload ONLY when field values have changed

What I'm trying to achieve is to Warn the user of unsaved changes if he/she tries to close a page or navigate away from it without saving first.
I've managed to get the OnBeforeUnload() dialog to pop-up... but I don't want it to be displayed at all if the user hasn't modified any field values. For this, I'm using this hidden input field called is_modified that starts with a default value of false and flips to true when any field is edited.
I tried to bind the change event to this is_modified field to try and detect for value change... and only then activate OnBeforeUnload.
$( '#is_modified' ).change( function() {
if( $( '#is_modified' ).val() == 'true' )
window.onbeforeunload = function() { return "You have unsaved changes."; }
});
But from what I figure is that the change() event works only after these 3 steps - a field receives focus, a value is changed and the field looses focus. In case of the hidden input field, I'm not sure how this receiving and loosing focus part works! Hence, the onbeforeunload function is never being activated.
Can anyone suggest a way to maintain a trigger over is_modified?
Thanks.
I had a similar requirement so came up with following jQuery script:
$(document).ready(function() {
needToConfirm = false;
window.onbeforeunload = askConfirm;
});
function askConfirm() {
if (needToConfirm) {
// Put your custom message here
return "Your unsaved data will be lost.";
}
}
$("select,input,textarea").change(function() {
needToConfirm = true;
});
The above code checks the needToConfirm variable, if its true then it will display warning message.
Whenever input, select or textarea elements value is changed, needToConfirm variable is set to true.
PS: Firefox > 4 don't allow custom message for onbeforeunload.
Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=588292
UPDATE: If you are a performance freak, you will love #KyleMit's suggestion.
He wrote a jQuery extension only() which will be executed only once for any element.
$.fn.only = function (events, callback) {
//The handler is executed at most once for all elements for all event types.
var $this = $(this).on(events, myCallback);
function myCallback(e) {
$this.off(events, myCallback);
callback.call(this, e);
}
return this
};
$(":input").only('change', function() {
needToConfirm = true;
});
The following works well in jQuery:
var needToConfirm = false;
$("input,textarea").on("input", function() {
needToConfirm = true;
});
$("select").change(function() {
needToConfirm = true;
});
window.onbeforeunload = function(){
if(needToConfirm) {
return "If you exit this page, your unsaved changes will be lost.";
}
}
And if the user is submitting a form to save the changes, you might want to add this (change #mainForm to the ID of the form they're submitting):
$("#mainForm").submit(function() {
needToConfirm = false;
});
We just use Window.onbeforeunload as our "changed" flag. Here's what we're doing, (using lowpro):
Event.addBehavior({
"input[type=radio]:change,input[type=text]:change,input[type=checkbox]:change,select:change": function(ev) {
window.onbeforeunload = confirmLeave;
}
".button.submit-button:click": function(ev) {
window.onbeforeunload = null;
},
});
function confirmLeave(){
return "Changes to this form have not been saved. If you leave, your changes will be lost."
}
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').live('click',function() {
$(window).unbind('beforeunload');
});
Above works For me.
Try your logic in a different manner. Meaning, put the logic for checking the value of the input field in your onbeforeunload method.
window.onbeforeunload = function () {
if ($("#is_modified").val() == 'true') {
return "You have unsaved changes.";
} else {
return true; // I think true is the proper value here
}
};
in IE9 you can use simple return statement (re) which will not display any dialogue box. happy coding..
why not have the onbeforeunload call a function that checks if the values have changed, and if so return the "unsaved changes" confirm?

Categories

Resources