Flowdock
method

observe_field

Importance_5
observe_field(field_id, options = {}) public

Observes the field with the DOM ID specified by field_id and calls a callback when its contents have changed. The default callback is an Ajax call. By default the value of the observed field is sent as a parameter with the Ajax call.

Required options are either of:

:url:url_for-style options for the action to call when the field has changed.
:function:Instead of making a remote call to a URL, you can specify a function to be called instead.

Additional options are:

:frequency:The frequency (in seconds) at which changes to this field will be detected. Not setting this option at all or to a value equal to or less than zero will use event based observation instead of time based observation.
:update:Specifies the DOM ID of the element whose innerHTML should be updated with the XMLHttpRequest response text.
:with:A JavaScript expression specifying the parameters for the XMLHttpRequest. The default is to send the key and value of the observed field. Any custom expressions should return a valid URL query string. The value of the field is stored in the JavaScript variable value.

Examples

  :with => "'my_custom_key=' + value"
  :with => "'person[name]=' + prompt('New name')"
  :with => "Form.Element.serialize('other-field')"

Finally

  :with => 'name'

is shorthand for

  :with => "'name=' + value"

This essentially just changes the key of the parameter.

:on:Specifies which event handler to observe. By default, it’s set to "changed" for text fields and areas and "click" for radio buttons and checkboxes. With this, you can specify it instead to be "blur" or "focus" or any other event.

Additionally, you may specify any of the options documented in link_to_remote.

Show source
Register or log in to add new notes.
September 26, 2008 - (v1.2.6 - v2.1.0)
5 thanks

Pass the observed fields value as a parameter in the Ajax request

Use encodeURIComponent with with to pass an encoded value as a parameter (POST or GET) of the AJAX request. For example:

<%= observe_field :company_id,

:url => {:action => ‘facilities’, :only_path => false}, :with => “‘company=’ + encodeURIComponent(value)” %> Also, setting only_path => false for the URL ensures that the full URL (including host and protocol) is used for the AJAX request.

November 7, 2008
3 thanks

Common options

“Common options” mentioned here is default PrototypeHelper options documented in link_to_remote

This means you can use :loading, :loaded, :failure, :success, etc in observe_field.

February 22, 2009
3 thanks

CAUTION! :frequency option description is misleading

To use event-based observer, don’t supply :frequency param at all. :frequency => 0 causes JS error.

Use this option only if time-based observer is what you need.