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