javascriptjqueryruby-on-railskeyupcharactercount

Rails: Using Jquery for Text_Area character count


My goal is to put the keycount in a blank 'p' element above a text_area. Here is my erb and javascript:

<div class="field">
  <p id="char-limit"></p>
  <%= f.label :essay %><br>
  <%= f.text_area :essay, :id => "essay-form" %>
</div>

(This is all I have in my javascript file by the way)

$("#essay-form").on("keyup", function() {
  var charCount = $("#essay-form").val().length;
  //The text in the p element with id char-limit is equivelent to num of chars
  $("#char-limit").html(charCount);
  if (charCount > 10) {
    $("#char-limit").css("color", "red");
  } else {
    $("#char-limit").css("color", "black");
  }
});

Only problem is, when I start typing, there is no number of characters count added into the char-limit p element.


Solution

  • Try this:

    function updateCounter(){
        var charCount = $("#essay-form").val().length;
        //The text in the p element with id char-limit is equivelent to num of chars
        $("#char-limit").html(charCount);
        if (charCount > 10) {
            $("#char-limit").css("color", "red");
         } else {
            $("#char-limit").css("color", "black");
         }
     };
    

    And

      <div class="field">
        <p id="char-limit"></p>
        <%= f.label :essay %><br>
        <%= f.text_area :essay, :id => "essay-form", onkeydown="updatecount()" %>
      </div>
    

    Hope this help. :)