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