Search code examples
ruby-on-railssimple-form

Add character counter in simple_form in Ruby on Rails


I use the simple_form gem and I want a simple character counter on a text field. I was told, this might work:

add this to the form:

<%= f.input :body, id: "body-field" %>
<span id="body-count">0 characters</span>

and javascript:

$("#body-field").on("keyup", function(){
length = $(this).val().length;
$("#body-count").html(length);
});

I got this information from here (Attention: It is full of advertisement): http://www.sohua.xyz/questions-full/4320915/how-do-i-implement-a-basic-character-counter-in-a-simple-form

I did this, but nothing happens. Here is my actual code chapters/new.html.erb:

    <%= simple_form_for([@book, @book.chapters.build]) do |f| %>
    <%= f.input :chaptertitle %>
    Mininmum amount of characters: <%= @book.min_length %> Maximum amount of characters: <%= @book.max_length %>
    <%= f.input :chaptercontent, id: "body-field" %>
    <span id="body-count">0 characters</span>
    <%= f.input :author %>
    <%= f.button :submit %>
<% end %>

    <script>
      $("#body-field").on("keyup", function(){
        length = $(this).val().length;
        $("#body-count").html(length);
      });
    </script>

Can you give me any advice, how to get it work?


Solution

  • You need to wrap your code in jquery document ready function:

    $(function() {
      $("#body-field").on("keyup", function(){
        var length = $(this).val().length;
    
        $("#body-count").html(length);
      });
    });
    

    Why don't you use an existing library instead? https://github.com/dtisgodsson/jquery-character-counter