简体   繁体   English

如何在Rails中实现字计数器?

[英]How to implement a word counter in Rails?

I'm wanting to implement a real-time word counter in a form. 我想在表单中实现一个实时字计数器。 So as a user types into the box, a line below the box updates with the correct number of words. 因此,当用户在框中键入内容时,框下方的一行会更新正确的单词数。

Here is the relevant form code (my views are .html.haml): 这是相关的表单代码(我的观点是.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" }

So below this description box, I'd like to count the number of words and display an 'out of 25' notice. 所以在这个描述框下面,我想计算单词的数量并显示“满分25”的通知。

I'm assuming that this is just some javascript I need to add, but I don't know where to proceed from here. 我假设这只是我需要添加的一些JavaScript,但我不知道从哪里开始。

Rails 3.2.11, Ruby 1.9.7 Rails 3.2.11,Ruby 1.9.7

Thanks! 谢谢!

It shouldn't be too difficult, you would need a div that had its content updated on the keyup event for the input box: 它应该不会太难,你需要一个div,它的内容在输入框的keyup事件上更新:

This is a little bit from memory and may need some adjustment but it should get you on the right path: 这有点来自内存,可能需要一些调整,但它应该让你走在正确的道路上:

= fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }, :onkeyup => "update_word_count(this);"

I think this is the right haml syntax, please correct me if not: 我认为这是正确的haml语法,如果不是,请纠正我:

#word-count-container 

The intended html: 预期的html:

<div id="word-count-container"></div>

Javascript: 使用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>

Alternative UJS approach (remove the onkeyup tag from the input): 替代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>

This seems like something that you have to validate on the server side as well as the client side. 这似乎是你必须在服务器端和客户端验证的东西。 So don't forget to do that. 所以不要忘记这样做。

validates :short_statement, length: { maximum: 25 }

If you want strict word counting you can use the Words Counted gem. 如果你想要严格的字数统计,你可以使用Words Counted gem。 Disclaimer I wrote it. 免责声明我写的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM