Skip to content

Instantly share code, notes, and snippets.

@binarygit
Created October 18, 2022 18:59
Show Gist options
  • Save binarygit/7c60cc115745d8673ceab8013054aec1 to your computer and use it in GitHub Desktop.
Save binarygit/7c60cc115745d8673ceab8013054aec1 to your computer and use it in GitHub Desktop.
Dirty Form using StimulusJs
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