javascript - rails : Using Jquery for Text_Area character count

标签 javascript jquery ruby-on-rails keyup charactercount

我的目标是将键计数放在文本区域上方的空白“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");
  }
});

唯一的问题是,当我开始输入时,没有将字符数添加到 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>

希望这有帮助。 :)

关于javascript - rails : Using Jquery for Text_Area character count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37107197/

相关文章:

javascript - github 上的 Angular 全栈示例

javascript - 在 Electron 中访问剪贴板

ruby-on-rails - 在 Ruby on Rails 中本地化包含数字的文本字段

javascript - Visual Studio IIS 工作正常,但在 IIS 7 脚本中托管时获取错误的 URL?

javascript - 使用 CSS : How to auto layout events 创建日历控件

javascript - jQuery Animate 队列 False 不工作

jquery:maskedinput 插件与验证插件配合不佳

javascript - 使用对象循环遍历数组

ruby-on-rails - 在救援中输出错误 (Ruby/Rails)

ruby-on-rails - 你怎么能让一个数字等于一个范围?