Rails:使用Jquery进行Text_Area字符计数

Rails: Using Jquery for Text_Area character count

本文关键字:Area 字符 Text 使用 Jquery 进行 Rails      更新时间:2023-09-26

我的目标是将keycount放在text_area上方的空白'p'元素中。这是我的erb和javascript:

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

(顺便说一句,这是我javascript文件中的全部内容)

$("#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");
  }
});

唯一的问题是,当我开始键入时,并没有将字符数count添加到char limit p元素中。

试试这个:

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");
     }
 };

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

希望得到帮助。:)