Implement character count as Stimulus controller

This commit is contained in:
Andreas Nedbal 2022-10-02 22:09:34 +02:00
parent 58d8c827e0
commit ff5210a891
1 changed files with 36 additions and 0 deletions

View File

@ -0,0 +1,36 @@
import { Controller } from '@hotwired/stimulus';
export default class extends Controller {
static targets = ['input', 'counter', 'action'];
declare readonly inputTarget: HTMLInputElement;
declare readonly counterTarget: HTMLElement;
declare readonly actionTarget: HTMLInputElement;
static values = {
max: Number
};
declare readonly maxValue: number;
connect(): void {
this.inputTarget.addEventListener('input', this.update.bind(this));
}
update(): void {
this.counterTarget.innerHTML = String(`${this.inputTarget.value.length} / ${this.maxValue}`);
if (this.inputTarget.value.length > this.maxValue) {
if (!this.inputTarget.classList.contains('is-invalid') && !this.actionTarget.disabled) {
this.inputTarget.classList.add('is-invalid');
this.actionTarget.disabled = true;
}
}
else {
if (this.inputTarget.classList.contains('is-invalid') && this.actionTarget.disabled) {
this.inputTarget.classList.remove('is-invalid');
this.actionTarget.disabled = false;
}
}
}
}