Rails 3: Can't get this jquery working on my form
I found a jquery snippet of code for counting down the characters when you type in a form. I've tried adding it to my application.js file but its not working. When I type in the textarea the number 350 doesn't change.
I've already installed jquery-rails and I use <%= javascript_include_tag :all %> so that shouldn't be the issue. Here's what I have in my application.js
$('textarea').keyup(function(){
ta = $(this);
if(ta.val().length >= 350){
ta.val( ta.val().substr(0, 350) );
} else {
$("#counter span").text(350-ta.val().length);
}
});
setInterval('$("#counter span").text(350-ta.val().length);', 350);
In my view I have :
<%= form_for @post, :validate => true, :html => {:multipart => true} do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :title, 'Title:' %><br />
<%= f.text_field :title %><br />
<%= f.label :image, "Choose image"%><br />
<%= image_tag(@post.image_url(:avatartiny).to_s) if @post.image? %>
<%= f.file_field :image %>
<%= f.hidden_field :image_cache %><br />
<%= f.label :content %><br />
<%= f.text_area :content %><br />
<div id="counter"><span>350</span> characters remaining.</div>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
And in my 开发者_如何学Ccustom.css I have:
textarea {
width:400px;
height:400px;
border:1px solid #999;
border-radius:3px;
padding:7px;
}
#counter span { font-weight:700 }
Here is what my html source says:
<form accept-charset="UTF-8" action="/posts" class="new_post" data-validate="true"
enctype="multipart/form-data" id="new_post" method="post" novalidate="novalidate"><div
style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input
name="authenticity_token" type="hidden" value="V6J0VERvuoKvQ5kXXgBuU5aC6VsKQ7W6RF30IKy9D7E="/></div>
<div class="field">
<label for="post_title">Title:</label><br />
<input data-validate="true" id="post_title" name="post[title]" size="30" type="text" /><br />
<label for="post_image">Choose image</label><br />
<input data-validate="true" id="post_image" name="post[image]" type="file" />
<input id="post_image_cache" name="post[image_cache]" type="hidden" /><br />
<label for="post_content">Content</label><br />
<textarea cols="40" id="post_content" name="post[content]" rows="20"></textarea><br />
<div id="counter"><span>350</span> characters remaining.</div>
</div>
Wrap your textarea binding in a document.ready binding:
$(function() {
$('textarea').keyup(function(){
ta = $(this);
if(ta.val().length >= 350){
ta.val( ta.val().substr(0, 350) );
} else {
$("#counter span").text(350-ta.val().length);
}
});
});
Does that work?
There's nothing wrong with your javascript so maybe try putting your code inside a
$(document).ready(function(){
});
block.
精彩评论