Stimulus Rails - Count characters in input field
** Disclaimer: I’m still experimenting with Stimulus and this might not be the best way to do things **
Prerequisites:
- rails 6
- stimulus 2
Final solution demo:
HOWTO:
/app/javascript/controllers/countchar_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "name", "counter" ]
countCharacters(event) {
let characters = this.nameTarget.value.length;
this.counterTarget.innerText = characters;
}
}
/app/views/posts/_form.html.erb
<div data-controller="countchar">
<%= form.text_area :content, data: { countchar_target: 'name', action: 'keyup->countchar#countCharacters' } %>
Characters: <span data-countchar-target='counter'><%= post.content.to_s.size %></span>
</div>
Did you like this article? Did it save you some time?