JavaScript Prototype Help?

I have a form with a text area. I want to have an observer watch the
text area and update a div with the running count of characters in
the text area. I tried “onchange” but that doesn’t update until you
leave the text area. I was able to get it working using AJAX, but
it’s silly to make a needless round trip to the server, when the page
already knows everything it needs to know. What I wanted was an
element observer which executes JavaScript immediately. So I decided
to write my own helper using the observe_field code as a model.

In my view I have:

<%= observe_field_length(‘text_area’, {
:frequency => 5,
:update => ‘count_display’,
:with => “'Current characters = ’ + value.length”}) %>

And obviously I also have the form text area called “text_area” and a
div called “count_display”.

My helper looks like this:

def observe_field_length(field_id, options = {})
options[:content] = options[:with] || ‘value’
callback = update_element_function("#{options[:update]}", options)
javascript = "new Form.Element.Observer(’#{field_id}’, "
javascript << "#{options[:frequency]}, "
javascript << “function(element, value) {”
javascript << “#{callback}}”
javascript << “)”
javascript_tag(javascript)
end

This does half the job: it updates the div while the user types, but
instead of evaluating the JavaScript in options[:content] it’s
outputting the string I want evaluated. I need a way to evaluate the
JavaScript in options[:content]. I’m 99% sure my answer lies in the
JavaScript Prototype Library but I can’t seem to find it. The AJAX
helper observe_field manages to evaluate the JavaScript sent to it in
options[:with]. How can I do the same thing?

Kevin S.

On 2/3/06, Kevin S. [email protected] wrote:

    javascript_tag(javascript)

end

Andrew’s solution is what I would do myself… but I thought I would
mention that another way to write the above is:
javascript = <<-CODE
new Form.Element.Observer(‘#{field_id}’,
#{options[:frequency]},
function(element, value) {
#{callback}} )
CODE

“CODE” can be any string you make up, like JAVASCRIPT, or JACK_DANIELS.

On Friday, February 03, 2006, at 4:17 PM, Kevin S. wrote:

I have a form with a text area. I want to have an observer watch
the text area and update a div with the running count of characters
in the text area.

You probably don’t need to bother with Rails helpers here at all. See
this example:
http://javascript.internet.com/forms/limit-textarea.html