Reputation: 509
I've been asked to implement a feature ...
Here is an example of the code used in the solution. The hasChanged
variable is what controls whether or not the page can be reloaded with or without a message. The variable doesn't seem to get updated before the window is unloaded in FF and IE, but does in Chrome.
The inline submit call was already there. I'm not sure why - that portion was inherited:
HTML:
<form id="form" method="post" action="http://www.google.com">
<textarea class="watch" name="" id="" cols="30" rows="10"></textarea>
</form>
<br><br>
<div class="submit disabled">
<a class="" href="#" onclick="$('#form').submit();$(this).text('saving...');">Submit</a>
</div>
JS:
var hasChanged=false;
$('textarea.watch').on('keyup change', function(){
hasChanged = true;
$('.submit').removeClass('disabled');
});
$('.submit a').click(function() {
hasChanged = false;
window.removeEventListener('beforeunload');
});
window.addEventListener('beforeunload', function (e) {
var confirmationMessage = 'You have unsaved changes.';
if (hasChanged) {
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
}
});
CSS:
.disabled a {
pointer-events: none;
color:#aaa;
text-decoration:none;
}
I've tried to unbind beforeunload on the "Submit" button before the submit function is called, but that didn't seem to work:
<a class="" href="#" onclick="$(window).unbind('beforeunload');('#form').submit();$(this).text('saving...');">Submit</a>
Issue in action (open in Chrome, then Firefox/IE): FIDDLE
Upvotes: 0
Views: 1620
Reputation: 108500
The problem is probably because you have inline onClick
logic that gets executed in different order in FF/Chrome. There is also across-origin error with posting a form to google, and it can behave differently in browsers.
Also, you don’t need to unbind the event, the hasChanged
variable is supposed to take care of that (if I understand the logic correctly). And if you unbind the event, you need to bring in the function as argument (see the other answer).
See this demo: http://jsfiddle.net/L4Gzs/15/
$('.submit a').click(function() {
hasChanged = false;
$('#form').submit();
$(this).text('saving...');
});
Upvotes: 1