如何在simple_form中实现基本字符计数器

How do I implement a basic character counter in a simple_form?

本文关键字:实现 字符 计数器 form simple      更新时间:2023-09-26

我的表单使用simple_form,并且希望在文本字段上启用一些基本的JS字符计数。

我的表单部分如下:

<%= simple_form_for(@post, html: {class: 'form-horizontal' }) do |f| %> 
    <%= f.error_notification %>
    <%= f.input_field :parent_id, as: :hidden %>
    <div class="field">
    <% if can? :manage, @post %>
            <%= f.input_field :status, label: "Status", collection: Post.statuses.keys, selected: :unconfirmed %>   
    <% end %>       
    </div>
    <%= f.input :title, placeholder: "Enter Title" %>
    <%= f.input :photo %>
        <%= f.input :file %>
    <%= f.input :body %>
        <div class="report-submit">
            <%= f.button :submit %>
        </div>
<% end %>

我该怎么做?

将一个id分配给文本字段,然后在其旁边添加一个span,您将在其中显示计数器,并将id分配给跨度。

<%= f.input :body, id: "body-field" %>
<span id="body-count">0 characters</span>

在Javascript中添加以下代码

$("#body-field").on("keyup", function(){
    length = $(this).val().length;
    $("#body-count").html(length);
});

我制作了一把小提琴来展示它的工作原理,点击这里http://jsfiddle.net/L99c30qh/