mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-01-31 21:37:16 +00:00
Add a simple CheckboxDisplay controller that show/hide content
depending on the checkbox state (checked or not)
This commit is contained in:
37
app/webpacker/controllers/checkbox_display_controller.js
Normal file
37
app/webpacker/controllers/checkbox_display_controller.js
Normal 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";
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user