jquery form validation, and submit-on-change
Posted
by
Bee
on Stack Overflow
See other posts from Stack Overflow
or by Bee
Published on 2012-09-26T23:27:27Z
Indexed on
2012/09/27
3:37 UTC
Read the original article
Hit count: 208
I want to make all my settings forms across my site confirm that changes are saved, kinda like facebook does if you make changes in a form and then try to navigate away without saving. So I'm disabling the submit button on the forms only enabling if the values change. I then prompt the user to hit save before they leave the page in the case that they do have changes pending.
var form = $('form.edit');
if(form.length > 0) {
var orig_str = form.serialize();
$(':submit',form).attr('disabled','disabled');
form.on('change keyup', function(){
if(form.serialize() == orig_str) {
setConfirmUnload(false);
$(':submit',form).attr('disabled','disabled');
} else {
setConfirmUnload(true);
$(':submit',form).removeAttr('disabled')
}
});
$('input[type=submit]').click(function(){ setConfirmUnload(false); });
}
function setConfirmUnload(on) {
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
return 'If you navigate away from this page without saving your changes, they will be lost.';
}
One of these forms needs some additional validation which I do using jQuery.validate library. e.g. if i wanted to ensure the user can't double submit the form on accident by double clicking on submit or somesuch (the actual validation in question is for a credit-card form and not this simple):
$('form').validate({
submitHandler: function(form) {
$(':submit', form).attr('disabled','disabled');
form.submit();
}
});
Unfortunately both bits are trying to bind to submit button and they're interfering with each other such that the submit button remains disabled no matter what I do and it is impossible to submit the form at all.
Is there some way to chain the validations together or something? Or some other way to avoid re-writing the validation code to repeat the "did you change anything in the form" business?
© Stack Overflow or respective owner