document.addEventListener('DOMContentLoaded', function(){ function exitWarning(e){ e.preventDefault(); } function setExitWarning(){ window.addEventListener('beforeunload', exitWarning ); this.removeEventListener('change', setExitWarning ); } var forms = document.querySelectorAll('main form'); for ( var i = 0, l = forms.length; i < l; i++ ) { forms[i].addEventListener('change', setExitWarning ); forms[i].querySelector('input[type=submit]').addEventListener('click', function(){ window.removeEventListener('beforeunload', exitWarning ); }); } });