在我的Ruby on Rails应用程序中,我试图在视图中显示以下文本框的剩余字符数:
<%= f.label :review_text, 'Review Text:' %>
我正试图通过这个java来做到这一点:
$(document).ready(function() {
$("#review_text").keyup(function() {
$("#counter").text(2000 - $(this).val().length);
});
});
显示剩余金额:
chars left : <span id="counter"><%= maxcounter=2000 %></span>
这不起作用,但此文本字段会:
<%= text_field_tag :review_text %>
如果我将上述内容更改为:
<%= f.text_field_tag :review_text %>
我得到以下错误:
NoMethodError in Reviews#new
undefined method `text_field_tag' for <ActionView::Helpers::FormBuilder:0x6b44020>
有人能帮忙吗。
以下是全貌:
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<div id="contentWrapper">
<div id="content">
<div class='large_panel'>
<table>
<%= form_for @review do |f| %>
<%= f.hidden_field :user_id %>
<%= f.hidden_field :film_id %>
<%= image_tag "thor_hammer.jpg",:size => "900x250" %>
<h1>REVIEW <%= @review.film.title %>:</h1>
<tr>
<td width="500px">
<%= f.label :review_text, 'Review Text:' %></br>
</td>
</tr>
<tr>
<td>
<%= f.text_area :review_text, :size=>"50x10" %></br></br>
</td>
</tr>
<tr>
<td width="100px">
<%= f.label :no_of_stars, 'Stars:' %></br>
</td>
</tr>
<tr>
<td>
<%= f.select :no_of_stars, 1..5 %></br></br>
</td>
</tr>
<tr>
<td>
chars left : <span id="counter"><%= maxcounter=2000 %></span>
<%= text_field_tag :review_text %>
<div class="actions">
<%= f.submit 'Submit' %>
</div>
<div class="actions">
<%= link_to 'Back', reviews_path %>
</div>
</br></br>
<%= render "/error_messages", :message_header => "Cannot save: ", :target => @review %>
</td>
</tr>
<% end %>
</table><br>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#review_text").keyup(function() {
$("#counter").text(2000 - $(this).val().length);
});
});
</script>
最佳答案
测试和工作:
审查u controller.rb:
class ReviewsController < ApplicationController
def new
@review = Review.new
@maximum_length = Review.validators_on( :review_text ).first.options[:maximum]
end
end
审查.rb
class Review < ActiveRecord::Base
validates :review_text, length: { maximum: 200 }
end
新建.html.erb
<%= form_for @review do |f| %>
<%= f.text_field :review_text, maxlength: @maximum_length, id: 'review_text' %>
Chars left: <span id="counter" data-maximum-length="<%= @maximum_length %>"><%= @maximum_length %></span>
<% end %>
<script>
$(document).ready(function() {
var review_text = $("#review_text");
var counter = $("#counter");
var max_length = counter.data("maximum-length");
review_text.keyup(function() {
counter.text(max_length - $(this).val().length);
});
});
</script>
关于javascript - Ruby on Rails显示f.text_area剩余的字符数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29017809/