UNPKG

@stimulus-library/controllers

Version:

A library of useful controllers for Stimulus

29 lines (28 loc) 1.25 kB
import { BaseController } from "@stimulus-library/utilities"; import { useCollectionEventListener } from "@stimulus-library/mixins"; export class LimitedSelectionCheckboxesController extends BaseController { connect() { useCollectionEventListener(this, this.inputTargets, "change", this._handleInputs); } _handleInputs(event) { const tickedInputs = this.inputTargets.reduce((previousValue, el) => el.checked ? previousValue + 1 : previousValue, 0); const target = event.target; if (tickedInputs > this.maxValue) { event.preventDefault(); target.checked = false; this.dispatchEvent(target, "change"); this.dispatchEvent(target, this.eventName("too-many")); if (this.hasErrorTarget && this.hasMessageValue) { this.errorTarget.innerHTML = this.messageValue; } } else { this.dispatchEvent(target, this.eventName("selection")); if (this.hasErrorTarget) { this.errorTarget.innerHTML = ""; } } } } LimitedSelectionCheckboxesController.targets = ["input", "error"]; LimitedSelectionCheckboxesController.values = { max: Number, message: String };