Skip to content

Instantly share code, notes, and snippets.

@somazx
Created March 29, 2023 13:42
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 somazx/62df141c61fab713395ebbe1d143b544 to your computer and use it in GitHub Desktop.
Save somazx/62df141c61fab713395ebbe1d143b544 to your computer and use it in GitHub Desktop.
Max Length for Input - Stimulus Controller
import { Controller } from "stimulus";
export default class extends Controller {
static targets = ["counter", "input"];
connect() {
this.updateCounter();
}
trackLength() {
this.updateCounter();
}
get maxLength() {
return Number(this.inputTarget.getAttribute("data-maxlength"));
}
updateCounter() {
const count = this.inputTarget.value.length;
this.counterTarget.textContent = `${count} / max ${this.maxLength}`;
if (count > this.maxLength) {
this.counterTarget.classList.add("text-danger");
} else {
this.counterTarget.classList.remove("text-danger");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment