JavaScript multipage form onbeforeunload issue - javascript

I am putting together a quiz system using the multipage form jQuery script and I would like to be able to warn the user if tries to close the page. I managed to do this just fine using the code below:
$(document).ready(function($) {
window.onbeforeunload = function(){
return 'Sure you want to close the page?';
};
});
My problem is that when I try to submit the form and post the results I get the warning asking me if I want to navigate away from this page. This is the code:
$('#quizForm').formwizard({
validationEnabled: true,
focusFirstInput : true,
formOptions: {
beforeSubmit: window.onbeforeunload = null,
resetForm: true
}
});
What am I doing wrong?
LE: I created this fiddle maybe someone can help me out, I am running out of ideas.
http://jsfiddle.net/awLYY/5/

first, you don't need to wait for the DOM to be ready in order to attach an onbeforeunload handler.
second, since the onbeforeunload is a function, you can choose wither to return a string or return nothing in case you're submitting some data to the server
var isFormBeingSubmitted = false;
window.onbeforeunload = function() {
if( isFormBeingSubmitted ) {
return;
}
return 'Sure you want to close the page?';
};
// now before you submit your form, just enable the isFormBeingSubmitted
$('#quizForm').formwizard({
validationEnabled: true,
focusFirstInput : true,
formOptions: {
beforeSubmit: function() {
isFormBeingSubmitted = true;
return true;
},
resetForm: true
}
});

To answer my own question, all I had to do was to add to the formwizard options:
formPluginEnabled: true
Now everything is working fine. Thanks

Related

how to unbind onbeforeunload event on javascript function call and page refresh

Please help me how to unbind onbeforeunload event on javascript function call .
Also I want to unbind onbeforeunload on page refresh.
Actually I want to give pop up alert on page exit .For this I have successfully unbinded onbeforeunload from form submit button and anchor tags. Kindly help me. The code I have used is
var jQuery = jQuery.noConflict();
jQuery(document).ready(function() {
jQuery(window).bind("onbeforeunload", function() {
return confirm("Do you really want to close?")
}
);
jQuery('a').on('click', function() {
jQuery(window).unbind('onbeforeunload')
});
jQuery("form").submit(function() {
jQuery(window).unbind('onbeforeunload')
});
});
Thanks
Do some minor change in your code, it will be work
jQuery(document).ready(function () {
window.onbeforeunload = function () {
return confirm("Do you really want to close?")
};
jQuery('a').on('click', function () {
jQuery(window).unbind('onbeforeunload')
});
jQuery("form").submit(function () {
jQuery(window).unbind('onbeforeunload')
});
});
Check this on jqfiddler, Message pop-up showing on refresh click here

jquery beforeSubmit not working

Im using html5 capacities to read image width and height before submitting...
Well, this is not happening exactly, it seems like the time needed for the functions:
reader.readAsDataURL();
reader.onload = function();
image.onload = function();
To read the file is way too much than the time my form is able to wait before sending the pic.
I can check that the beforeSubmit function is triggered, but the form is submitted before it finishes.
Another weird thing is that I have replaced the beforeSubmit function content with a simple return false sentence and the form is being submitted anyway.
Am I missing something regarding the beforeSubmit option in ajaxSubmit?
The beforeSubmit function has been minimized to a return false statement, here comes the submit (the form is inside a dialog(), may be this the clue?:
$('.block .imgpop').on("click",function()
{
type = $(this).attr('emimage');
currentype = type;
options =
{
type: 'POST',
target: '#uploadverbose',
beforeSend: beforeSubmit,
resetForm: true,
success: showResponse,
data: { type: $(this).attr('emimage'), tempname: $(this).attr('id'), maxsize: imgsizesW[$(this).attr('emimage')] },
dataType : "text"
};
$('#uploadbitch').dialog(
{
closeOnEscape: true,
width: 800,
modal: true
});
return false;
});
$(document).on("click","#MyUploadForm input[type=submit]", function(e, submit)
{
if (!submit) e.preventDefault();
$('#MyUploadForm').ajaxSubmit(options);
});
$(document).on("submit","#MyUploadForm", function(e, submit)
{
e.preventDefault();
$('#MyUploadForm').ajaxSubmit(options);
});
If you try to handle onclick on submit button then it doesn't stop form from submitting.
It may bot be exactly the answer, but it works. I have place all the image testing in the input field with a "change" event and it works just fine for me. Precocity in the form submitting is still unsolved.

How to translate Protoype "Ajax.Responders.register" to jQuery

I have to translate some prototype code to jquery and and I don't know how to translate this part :
Ajax.Responders.register({
onCreate: function() {
$('working').show();
window.onbeforeunload = check_working;
},
onComplete: function() {
$('working').hide();
window.onbeforeunload = null;
}
});
In fact I found some pages which deal with this problem (Prototype - Are there AJAX start/stop events to global trigger an AJAX modal wait message? for instance) but I did this :
jQuery(document).ajaxSend(function() {
jQuery('#working').show();
window.onbeforeunload = check_working;
});
jQuery(document).ajaxStop(function() {
jQuery('#working').hide();
window.onbeforeunload = null;
});
And I don't know why but I never enter into the ajax.start and stop (I tried with console.log by doing the same things that I did with the previous version which works). And I have no error.
Do you have any ideas how to fix it ?
Thank you in advance.

jquery "return false" not working properly inside update panel

I used jquery to validate a text box placed within update Panel
$("[id*='btnCreate']").live('click', function ()
{
var regex = new RegExp("^[a-zA-Z0-9]+$");
if (!regex.test($("[id*='txtbxTemplateName']").val()))
{
alert('hit');
$("[id*='lblError']").text() = 'Template name is invalid!';
return false;
}
});
the click event function is being called, but after returning false it is still hitting the code behind.
Please help me on this.
I presume you mean by "still hitting the code behind" that the default action of the button is not being prevented. This is because the code never gets to return false because of an error:
$("[id*='lblError']").text() = 'Template name is invalid!';
return false;
should be
$("[id*='lblError']").text('Template name is invalid!');
return false;
You have just exposed, however, why return false is a bad way to prevent the default action of an event. It is bad because any errors in the error handler will mean that the default action is not prevented, because return false is the last statement in the handler.
If you use event.preventDefault(), all kinds of beautiful things will happen. Chief among them is that you can place the statement earlier in the handler:
$("[id*='btnCreate']").live('click', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
if (!regex.test($("[id*='txtbxTemplateName']").val())) {
event.preventDefault();
alert('hit');
$("[id*='lblError']").text('Template name is invalid!');
}
});

POST via ajax only if validation check returns true

I'm checking my form with RSV validator. Want to get work following: Let's say user opened page for the first time. After filling all text input boxes, when user clicks #submit_btn FOR THE FIRST TIME, the form submit function fires RSV (validator), validator checks if there is any error. If all right, posts data via ajax, else RSV shows error messages array with the help of alert(). THIS PROCEDURE ONLY FOR THE FIRST TIME
BTW: RSV - validator. If no error occured during validation process the myoncomplete() function returns 1.. If something went wrong it alerts. Got from here
I can't get it work. Please help me to fix logic/code mistakes. Thx in advance
My JS
var int=null;
var counter=0;
function myOnComplete() {
return 1;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Page name required",
"required,title,Page title required.",
]
});
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
int = setInterval(call, 3000);
var message = result.msg;
var err = result.err;
if (message != null) {
$.notifyBar({
cls: "success",
html: message
});
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
$("#submit_btn").click(function () {
if(counter===0){
if(myOnComplete()===1) $('#add_form').submit();
else return false;
}
else $('#add_form').submit();
counter++;
});
$('#autosave').click(function(){
if($(this).is(':checked')){
int = setInterval(call, 3000);
$('#submit_btn').attr({'value':'Save&Exit'});
}
else{
$('#submit_btn').attr({'value':'Save'});
clearInterval(int);
}
});
});
function call() {
$('#add_form').submit();
}
Looking through the RSV code it looks like whatever you attach RSV to has its submit rebound to validate the data using .RSV.validate()
As seen here:
$(this).bind('submit', {currForm: this, options: options}, $(this).RSV.validate);
});
Which means that if you use .submit() you are calling .RSV.validate also.
So once you validate the info try binding your submit to the standard submit function.
Edit: To help explain
When you use
$("#add_form").RSV({...});
The RSV javascript code is binding .RSV.validate() to the submit event of your add_form element. Meaning when you submit your add_form form .RSV.validate() is being called before the submit.
Try running the script code below with and without the .RSV() call
This script will log ALL handlers for ALL events on the add_form element. You notice that calling $element.RSV({...}) attaches a second event handler to the submit event of the add_form element. I am unsure of the best way to access this event handler to .unbind() it. Good luck :)
jQuery.each($('#add_form').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log(handler);
});
});
OK, to my understanding now you only want to validate the first set of data and if that validates correctly trust the user, i got this working on jsFiddle with an easy example, i guess you can make use of that
http://jsfiddle.net/WqnYa/9/
Basically what i do is that i catch the submit button click and not the forms submit function, maybe it can be done that way, too. I assign a class "needsvalidation" and when ever the first validation passes, i simply remove that class. And if that class is not present, the validation will not be initialized due to $(this).hasClass('needval')
If that's not what you're looking for then your question needs way more clarity :( hope this helps though!

Categories

Resources