Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cabgfx/d08d8d442d8dd9fe0aa67be190c52600 to your computer and use it in GitHub Desktop.
Save cabgfx/d08d8d442d8dd9fe0aa67be190c52600 to your computer and use it in GitHub Desktop.
import { Controller } from "stimulus";
export default class extends Controller {
static targets = ["count"];
connect() {
this.setCount();
}
checkAll() {
this.setAllCheckboxes(true);
this.setCount();
}
checkNone() {
this.setAllCheckboxes(false);
this.setCount();
}
onChecked() {
this.setCount();
}
setAllCheckboxes(checked) {
this.checkboxes.forEach((el) => {
const checkbox = el;
if (!checkbox.disabled) {
checkbox.checked = checked;
}
});
}
setCount() {
if (this.hasCountTarget) {
const count = this.selectedCheckboxes.length;
this.countTarget.innerHTML = `${count} selected`;
}
}
get selectedCheckboxes() {
return this.checkboxes.filter((c) => c.checked);
}
get checkboxes() {
return new Array(...this.element.querySelectorAll("input[type=checkbox]"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment