4

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?

Metaphysiker
  • 983
  • 2
  • 18
  • 35

3 Answers3

3

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

sidegeeks
  • 1,021
  • 3
  • 12
  • 17
  • I changed my code, but nothing happens. Do you have any further suggestions? About the existing library: I'm an amateur, I don't see from the link, what I need to change in my code, can you be more specific? Thank you very much – Metaphysiker Jan 16 '16 at 15:53
  • Have you added jquery turbolinks to your gemfile and manifest? https://github.com/kossnocorp/jquery.turbolinks – sidegeeks Jan 17 '16 at 08:01
3

You might want to use either js or coffee-script, I am providing a coffee script example below:

Add this piece of code to your chapters.coffee file:

ready = ->
  totalChars = 100
  #Total characters allowed
  countTextBox = $('#body-field')
  # Remaining chars count will be displayed here
  charsCountEl = $('#countchars')
  #initial value of countchars element
  charsCountEl.text totalChars
  #user releases a key on the keyboard
  countTextBox.keyup ->
    #get chars count in Text field
    thisChars = @value.replace(/{.*}/g, '').length
    if thisChars > totalChars
      # total extra chars to delete
      CharsToDel = thisChars - totalChars
      #remove excess chars from text field
      @value = @value.substring(0, @value.length - CharsToDel)
    else
      #count remaining chars
      charsCountEl.text totalChars - thisChars
    return
  return

$(document).ready ready
$(document).on 'page:load', ready
# Loads javascript while loading page

Add this line to your form right below to the Text input field.

var ready;
var charsCountEl, countTextBox, totalChars;
totalChars = 100;
countTextBox = $('#body-field');
charsCountEl = $('#countchars');
charsCountEl.text(totalChars);
countTextBox.keyup(function() {
  var CharsToDel, thisChars;
  thisChars = this.value.replace(/{.*}/g, '').length;
  if (thisChars > totalChars) {
    CharsToDel = thisChars - totalChars;
    this.value = this.value.substring(0, this.value.length - CharsToDel);
  } else {
    charsCountEl.text(totalChars - thisChars);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="body-field" />
<span id="countchars"></span>

If your file under javascript/ folder doesn't have extestion .coffee the please rename it to chapters.coffee if it does then thats it.

PS: here is the javascript version of the same http://pastebin.com/LZb1DAC4.

Reference: https://stackoverflow.com/a/24629105/2545197

Community
  • 1
  • 1
Abhinay
  • 1,796
  • 4
  • 28
  • 52
  • I did everything you suggested, but it doesn't work. Now, there stands "100", but nothing changes, when i type something in. Further suggestions? Do I need to do anything, to enable coffee script? I'm using Ruby on Rails 4. Thanks – Metaphysiker Jan 16 '16 at 15:50
  • @NadjaKuhn Do the inspect element and click on console tab see if there is some js errors. also make sure you dont have anyother javascript code running for body-field. – Abhinay Jan 16 '16 at 17:58
  • i think the problem you're facing is a turbolinks issue. Rails has that turned on by default. Add this gem - https://github.com/kossnocorp/jquery.turbolinks – sidegeeks Jan 17 '16 at 07:59
  • @sidegeeks I have tested this code against Turbolinks, its working fine..on top of it..`$(document).on 'page:load', ready` aligns well with turbolinks. – Abhinay Jan 17 '16 at 12:35
  • @Abhinay thanks for the example. What is the correct way to initialize the countchars to be (totalChars - countTextBox.length)? Try the following was unsuccessful - countTextBox.load -> thisChars = @ value.length charsCountEl.text totalChars - thisChars return – user553620 Sep 27 '16 at 06:20
  • Didn't get you @user553620. `countchars` is the `id` of the `span` where you want to display the remaining characters. – Abhinay Sep 27 '16 at 06:24
  • Hey @user553620 just updated my answer with snippet example please check. let me know if you need more help on this. good luck. – Abhinay Sep 27 '16 at 06:37
  • @Abhinay thanks for the followup. I fixed the issue by changing the initial value to the following : charsCountEl.text totalChars - countTextBox.val().length. With this change the number of remaining characters is set to correct value in both the 'new' and 'edit' view forms. Thanks again for the wonderful coffeescript snippet. – user553620 Oct 01 '16 at 05:55
  • @user553620 I am glad it worked!! Feel free to ping if you encounter such issue in the future. – Abhinay Oct 01 '16 at 06:10
0

This solution won't be as good as Abhinay's solution, but it works for me: (Please note, I'm an amateur, this code may be horrendous)

Javascript code:

<script>

  $(document).ready(function(){

    var choosingbar = function( event ){
      $(event.target).parents(".counting").children(".count").text($(event.target).val().length);
    };

    $(".counting textarea").keyup(choosingbar);
  });

</script>

new.html.erb code:

<%= 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 %>
    <div class="counting" ><%= f.input :chaptercontent %>Characters: <span class="count"></span></div><br>
    <%= f.input :author %>
    <%= f.button :submit %>
<% end %>
Metaphysiker
  • 983
  • 2
  • 18
  • 35
  • Do you mind accepting anyone one of the answer as a solution to this question. it will bring this question to resolved category instead of unanswered. – Abhinay Jan 27 '16 at 04:09