Created
October 18, 2022 18:59
-
-
Save binarygit/7c60cc115745d8673ceab8013054aec1 to your computer and use it in GitHub Desktop.
Dirty Form using StimulusJs
This file contains 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
import ApplicationController from "./application_controller"; | |
const LEAVING_PAGE_MESSAGE = "Are you sure you want to leave?"; | |
export default class extends ApplicationController { | |
static values = { dirty: Boolean }; | |
static targets = ["submitBtn"]; | |
connect() { | |
// find all inputs within the form | |
// and attach eventListeners | |
this.inputs = this.element.querySelectorAll("input"); | |
this.inputs.forEach((input) => { | |
let boundFunc = this.makeDirty.bind(this); | |
input.addEventListener("change", boundFunc); | |
}); | |
// find all anchor tags that link locally | |
// and ask confirmation when they are clicked | |
this.localLinks = document.querySelectorAll("a[href^='#']"); | |
this.localLinks.forEach((el) => { | |
let boundFunc = this.leavingPage.bind(this); | |
el.addEventListener("click", boundFunc); | |
}); | |
} | |
makeDirty() { | |
this.dirtyValue = true; | |
} | |
leavingPage(event) { | |
if (this.dirtyValue) { | |
let confirmation = confirm(LEAVING_PAGE_MESSAGE); | |
if (!confirmation) { | |
event.preventDefault(); | |
} | |
} | |
} | |
dirtyValueChanged() { | |
// enable submit button if there is a target and | |
// the form is dirty | |
if (this.hasSubmitBtnTarget) { | |
if (this.dirtyValue) this.submitBtnTarget.removeAttribute("disabled"); | |
} | |
} | |
disconnect() { | |
this.inputs.forEach((input) => | |
input.removeEventListener("change", this.makeDirty) | |
); | |
this.localLinks.forEach((el) => | |
el.removeEventListener("click", this.leavingPage) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment