diff --git a/app/webpacker/controllers/checkbox_display_controller.js b/app/webpacker/controllers/checkbox_display_controller.js new file mode 100644 index 0000000000..ae82b46224 --- /dev/null +++ b/app/webpacker/controllers/checkbox_display_controller.js @@ -0,0 +1,37 @@ +import { Controller } from "stimulus"; + +export default class extends Controller { + static values = { targetId: String }; + + connect() { + this.element.addEventListener("change", this.change.bind(this)); + if (this.element.checked) { + this.showTarget(); + } else { + this.hideTarget(); + } + } + + disconnect() { + this.element.removeEventListener("change", this.change.bind(this)); + } + + change(event) { + // if the checkbox is checked, display the target + if (this.element.checked) { + this.showTarget(); + } else { + this.hideTarget(); + } + } + + showTarget() { + let target = document.getElementById(this.targetIdValue); + target.style.display = "block"; + } + + hideTarget() { + let target = document.getElementById(this.targetIdValue); + target.style.display = "none"; + } +} diff --git a/spec/javascripts/stimulus/checkbox_display_controller_test.js b/spec/javascripts/stimulus/checkbox_display_controller_test.js new file mode 100644 index 0000000000..2af8fad59c --- /dev/null +++ b/spec/javascripts/stimulus/checkbox_display_controller_test.js @@ -0,0 +1,39 @@ +/** + * @jest-environment jsdom + */ + +import { Application } from "stimulus"; +import checkbox_display_controller from "../../../app/webpacker/controllers/checkbox_display_controller"; + +describe("CheckboxDisplayController", () => { + beforeAll(() => { + const application = Application.start(); + application.register("checkbox-display", checkbox_display_controller); + }); + + describe("#toggle", () => { + beforeEach(() => { + document.body.innerHTML = `