gpt4 book ai didi

javascript - Ruby on Rails 显示 f.text_area 的剩余字符数

转载 作者:太空宇宙 更新时间:2023-11-03 17:22:29 24 4
gpt4 key购买 nike

在我的 Ruby on Rails 应用程序中,我试图在 View 中显示以下文本框的剩余字符数:

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

最佳答案

测试和工作:

评论 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com