[英]How to implement a word counter in Rails?
我想在表單中實現一個實時字計數器。 因此,當用戶在框中鍵入內容時,框下方的一行會更新正確的單詞數。
這是相關的表單代碼(我的觀點是.html.haml):
= f.semantic_fields_for :student_biography do |fb|
= fb.inputs :name => "About" do
= fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }
所以在這個描述框下面,我想計算單詞的數量並顯示“滿分25”的通知。
我假設這只是我需要添加的一些JavaScript,但我不知道從哪里開始。
Rails 3.2.11,Ruby 1.9.7
謝謝!
它應該不會太難,你需要一個div,它的內容在輸入框的keyup事件上更新:
這有點來自內存,可能需要一些調整,但它應該讓你走在正確的道路上:
= fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }, :onkeyup => "update_word_count(this);"
我認為這是正確的haml語法,如果不是,請糾正我:
#word-count-container
預期的html:
<div id="word-count-container"></div>
使用Javascript:
<script type="text/javascript">
function update_word_count(object) {
words = object.value.match(/\S+/g).length.toString();
$('#word-count-container').innerHTML = words + " out of 25 used";
}
</script>
替代UJS方法(從輸入中刪除onkeyup標記):
<script type="text/javascript">
$('#short_statement').onkeyup(function() {
update_word_count(this);
});
function update_word_count(object) {
words = object.value.match(/\S+/g).length.toString();
$('#word-count-container').innerHTML = words + " out of 25 used";
}
</script>
這似乎是你必須在服務器端和客戶端驗證的東西。 所以不要忘記這樣做。
validates :short_statement, length: { maximum: 25 }
如果你想要嚴格的字數統計,你可以使用Words Counted gem。 免責聲明我寫的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.