Save Changes Prompt
by skibulk
HTML
<form action="#">
<h1>Subscribe to our Newsletter</h1>
<p><label for="text1">Email Address</label></p>
<p><input type="text" name="text1" id="text1"></p>
<fieldset>
<legend>How often would you like to receive news?</legend>
<p>
<input type="radio" name="radio1" id="radioA" value="weekly" checked><label for="radioA">Weekly</label>
<input type="radio" name="radio1" id="radioB" value="quarterly"><label for="radioB">Quarterly</label>
</p>
</fieldset>
<p><label for="checkbox1">Would you like to receive coupons?</label> <input type="checkbox" name="checkbox1" id="checkbox1" /></p>
<p><label for="select1">Which are you?</label></p>
<p>
<select name="select1" id="select1">
<option value="consumer">Consumer</option>
<option value="business">Business</option>
</select>
</p>
<p><label for="textarea1">Questions or Comments</label></p>
<p><textarea name="textarea1" id="textarea1" cols="45" rows="5"></textarea></p>
<p><input type="submit" name="submit1" id="submit1" value="Submit" /></p>
</form>
CSS
.changed {
background: repeating-linear-gradient(
45deg,
#606dbc,
#606dbc 10px,
#465298 10px,
#465298 20px
);
}
JavaScript
function formUnloadPrompt(formSelector) {
var formA = $(formSelector).serialize(), formB, formSubmit = false;
// Detect Form Submit
$(formSelector).submit( function(){
formSubmit = true;
});
// Handle Form Unload
window.onbeforeunload = function(){
if (formSubmit) return;
formB = $(formSelector).serialize();
if (formA != formB) return "Your changes have not been saved.";
};
// Enable & Disable Submit Button
var formToggleSubmit = function(){
formB = $(formSelector).serialize();
$(formSelector+' [type="submit"]').attr( "disabled", formA == formB);
};
formToggleSubmit();
$(formSelector).change(formToggleSubmit);
$(formSelector).keyup(formToggleSubmit);
}
// Call function on DOM Ready:
$(function(){
formUnloadPrompt('form');
});