Reputation: 389
I have sourced (read copied and pasted) some code
var catcher = function() {
var changed = false;
$('form').each(function() {
if ($(this).data('initialForm') != $(this).serialize()) {
changed = true;
$(this).addClass('changed');
} else {
$(this).removeClass('changed');
}
});
if (changed) {
return 'One or more forms on this page have changed. Are you sure you want to leave this page?';
}
};
$(function() {
$('form').each(function() {
$(this).data('initialForm', $(this).serialize());
}).submit(function(e) {
var formEl = this;
var changed = false;
$('form').each(function() {
if (this != formEl && $(this).data('initialForm') != $(this).serialize()) {
changed = true;
$(this).addClass('changed');
} else {
$(this).removeClass('changed');
}
});
if (changed && !confirm('Another form on this page has been changed. Are you sure you want to continue with this form submission?')) {
e.preventDefault();
} else {
$(window).unbind('beforeunload', catcher);
}
});
$(window).bind('beforeunload', catcher);
});
Now...this code handles multiple forms... and cleverly recognises all methods of leaving a page, warning that there may be unsaved data.
Ive wrestled with the code but its beyond me.
What Im looking to do is
a) trigger an event immediatly some data is changed populating a div with 'Data Changed' rather than waiting for the page unload.
b) Potentially reduce the scripts capabilities to one form.
Any help, advice or ideas gratefully accepted.
Will
Upvotes: 0
Views: 260
Reputation: 5442
http://jsfiddle.net/colbycallahan/9rxLx/
Detect changes to inputs on form and fill a div with the changed inputs value:
$('#myForm').on('change', 'input, select', function(){
$('#div_id').text($(this).val());
});
Change the action of a form, reset it, and prevent it from submitting:
$('#myForm').on('submit', function(event){
event.preventDefault();
alert($(this).serialize());
alert('form action is: ' + $(this).attr('action'));
$('#myForm')[0].reset();
$('#myForm').attr('action', 'Your_New_Url');
return false;
});
Upvotes: 1