Form.confirmUnsaved()

Snippets are small pieces of code that do not fit in the UvumiTools plugin category. Please note that each of these semi-useful functions requires Mootools 1.2.

This function extends the Element object but will have no effect on any other element than <form>. It will prompt the user if he/she tries to leave the page after modifying a form without submitting it.
If the user modifies the form and presses the reset button, it will cancel the confirmUnsaved behavior and quietly let the user navigate away. Same thing if the form is submitted (in case your form is ajaxified).

Element.implement({
confirmUnsaved : function(){
if(this.get('tag') == 'form'){
this.addEvents({
'submit' : function(){this.store('modified',false);},
'reset' : function(){this.store('modified',false);}
}).getElements('input,textarea,select').addEvent('change',function(){
this.getParent('form').store('modified',true);
});
window.onbeforeunload = function(){
if(this.retrieve('modified')){
return "You did not submit the last modifications.";
}
}.bind(this);
}
return this;
}
});

Demo:

Type something in the text input. Then click this link (takes you back to this page if you decide to follow it). The reset button, which is a regular reset input, will cancel the prompt.

This example will not work in Safari or Chrome if your address bar already contains a #, it will just take you to the top of the page without reloading the document, because the link points to this same page. This is a very particular case. Try any other link on this page, and it will work fine.