Skip to content

Instantly share code, notes, and snippets.

@felds
Last active September 23, 2021 20:14
Show Gist options
  • Save felds/b72346e93c3fc2d2cadafe1d2334d351 to your computer and use it in GitHub Desktop.
Save felds/b72346e93c3fc2d2cadafe1d2334d351 to your computer and use it in GitHub Desktop.
Remove validation and prompt when exiting unsaved form
<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