Add a simple CheckboxDisplay controller that show/hide content

depending on the checkbox state (checked or not)
This commit is contained in:
Jean-Baptiste Bellet
2023-03-16 17:03:01 +01:00
parent 6fdf9fa038
commit 470761da86
2 changed files with 76 additions and 0 deletions

View File

@@ -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";
}
}

View File

@@ -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 = `<div >
<input type="checkbox" id="checkbox" data-controller="checkbox-display" data-checkbox-display-target-id-value="content" />
<div id="content">
content
</div>
</div>`;
});
it("show the content if the checkbox is checked, hide content either", () => {
const checkbox = document.getElementById("checkbox");
const content = document.getElementById("content");
expect(content.style.display).toBe("none");
checkbox.click();
expect(content.style.display).toBe("block");
checkbox.click();
expect(content.style.display).toBe("none");
});
});
});