Created
March 29, 2023 13:42
-
-
Save somazx/62df141c61fab713395ebbe1d143b544 to your computer and use it in GitHub Desktop.
Max Length for Input - Stimulus Controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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