0

我为我的表单使用了simple_form,并希望在文本字段上启用一些基本的JS字符计数。如何在simple_form中实现基本字符计数器?

我的形式部分看起来像这样:

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

我如何去这样做呢?

+0

哪里是大文本字段? – RSB 2014-09-02 09:34:51

+0

@RSB'f.input:body'。 – marcamillion 2014-09-02 09:36:02

回答

2

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/

+0

完美。非常感谢! – marcamillion 2014-09-02 10:41:54

+0

还有一个要求 - 我如何将其转换为字数计数器而不仅仅是字符计数器?这很简单吗? – marcamillion 2014-09-02 10:52:41