SyntaxHighlighter

Friday, May 29, 2009

Character count a textarea in Ruby on Rails

I used to do this with an 'onkeyup' attribute, but that's not available to the 'observe_field' method. But, by setting the frequency to a tenth of a second, it's much better. The character count updates even on keydown and hold.

In the view you just do this

Message (<span id='char_count' ></span > characters)<br>
<%= text_area_tag :description %>
<%= character_count('description','char_count', :frequency => 0.10) %>


And in the helper, you have a 'character_count' method.

def character_count(field_id, update_id, options = {})
function = "$('#{update_id}').innerHTML = $F('#{field_id}').length;"
out = javascript_tag(function) # set current length
out += observe_field(field_id, options.merge(:function => function)) # and observe it
end

2 comments:

  1. Thanks, Mark! I modified this a little and came up with a word count using your code as a starting point. Works great! Thanks, again!

    Here is the modified version that supports word count and both client and server-side validation:
    http://stufftohelpyouout.blogspot.com/2009/09/rubyrails-and-javascript-word-count.html

    ReplyDelete
  2. Thanks!
    I spent some time getting it to work, because of missing frequency. I would propose something like this into application_helper.rb:

    def character_count(field_id, update_id, options = {})
    function = "$('#{update_id}').innerHTML = $F('#{field_id}').length;"
    out = javascript_tag(function) # set current length
    options = {:frequency => 0.1, :function => function}.merge(options) # default options
    out += observe_field(field_id, options) # and observe it
    end

    Then the form could look like:

    <%= f.text_area(:message) %>
    <span id="post_message_count"></span>
    <%= character_count("post_message", "post_message_count") %>

    ReplyDelete