In my Ruby on Rails application I am trying to display the amount of characters remaining for the following text box in the view:
<%= f.label :review_text, 'Review Text:' %>
And am trying to do so through this java:
$(document).ready(function() {
$("#review_text").keyup(function() {
$("#counter").text(2000 - $(this).val().length);
});
});
Which displays the amount left through:
chars left : <span id="counter"><%= maxcounter=2000 %></span>
This does not work, but this text field does:
<%= text_field_tag :review_text %>
If I change the above to:
<%= f.text_field_tag :review_text %>
I get the following error:
NoMethodError in Reviews#new
undefined method `text_field_tag' for <ActionView::Helpers::FormBuilder:0x6b44020>
Can someone please help.
Below is the full view:
<%= 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>
Tested and working:
reviews_controller.rb :
class ReviewsController < ApplicationController
def new
@review = Review.new
@maximum_length = Review.validators_on( :review_text ).first.options[:maximum]
end
end
review.rb :
class Review < ActiveRecord::Base
validates :review_text, length: { maximum: 200 }
end
new.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>