Prototype UJS Character Counter

This following javascript provides Twitter-like feedback to users as to how many characters remain before the input field text limit is exceeded. The script will optionally truncate the input field if the character count exceeds the limit. It utilizes Prototype and is unobtrusive. An extra present: It supports multiple field/counter pairs on a page.

To deploy in a Rails app, place the counter.js script in your javascripts directory. Then include the script at the top of the form view:

<% content_for :head do -%>
  <%= javascript_include_tag('counter') %>
<% end -%>

The form itself should be generated by something like this:

<%= form_for(:product) do |f| -%>
  <%= f.label :description %>
  <%= f.text_area :description %>
  <%= label_tag :product_description_count, "Characters remaining:" %>
  <%= text_field_tag :product_description_count, 255, :class => 'text-count', :disabled => true %>
  <%= f.submit %>
<% end -%>


Blog comments powered by Disqus