gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:42:11 24 4
gpt4 key购买 nike

我想在表单中实现一个实时字计数器。因此,当用户在框中键入内容时,框下方的一行会更新为正确的单词数。

这是相关的表单代码(我的观点是.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

谢谢!

最佳答案

这应该不会太困难,您需要一个在输入框的 keyup 事件上更新其内容的 div:

这只是内存中的一点,可能需要一些调整,但它应该会让您走上正确的道路:

= 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>

关于javascript - 如何在 Rails 中实现字计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com