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 Skoglund