Last active
September 23, 2021 20:14
-
-
Save felds/b72346e93c3fc2d2cadafe1d2334d351 to your computer and use it in GitHub Desktop.
Remove validation and prompt when exiting unsaved form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
const forms = Array.from(document.querySelectorAll("form")) | |
// disable browser validation | |
forms.forEach(el => el.noValidate = true) | |
// add unsaved data prompt | |
let unsaved = false; | |
window.addEventListener("beforeunload", (e) => { | |
if (unsaved) { | |
e.preventDefault(); | |
e.returnValue = ""; | |
} else { | |
delete e['returnValue']; | |
} | |
}) | |
/** | |
* @param {HTMLFormElement} el | |
*/ | |
function markUnsaved(el) { | |
if (!el.target.dataset.ignoreUnsaved) unsaved = true; | |
} | |
/** | |
* @param {HTMLFormElement} el | |
*/ | |
function unmarkUnsaved(el) { | |
unsaved = false; | |
} | |
forms.forEach(el => { | |
el.addEventListener('change', markUnsaved); | |
el.addEventListener('submit', unmarkUnsaved); | |
}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment