Blah Blah Woof Woof

Archived content 2005-2007

observe_field for fields modified by javascript

Posted by Tim Riley Mon, 03 Apr 2006 09:17:00 GMT

The Rails PrototypeHelper observe_field is useful for calling JavaScript functions or sending XmlHttpRequests whenever a form field is modified.

For fields like checkboxes or radio buttons that have a limited number of states, it is fine for the observe_field callback to be triggered whenever a mouse click or keyboard event changes this state. On the other hand, for fields like text boxes, it makes more sense to provide a :frequency option to the helper, in which case it will check the field for a changed state at set intervals (a text box that triggered the callback with every letter typed would cause performance issues).

However, you can safely throw this rule out the window if you are using JavaScript to change the state of form fields. In this case, you definitely need to specify a :frequency option:


 <%= observe_field "field_id",
   :url => { :action => "foo" },
   :frequency => 0.25,
   :with => "'value='+ escape(value)" %>

The callback isn’t triggered when a state change is made with a script, but when the observer checks periodically, then the change will in the end be picked up and your callback request or function invoked.

Comments

  1. Rob Rix said 10 days later:

    You might also be able to just call the onChange method for the form field from your javascript that changes the value. Haven’t tried it but it’s worth a shot.

Trackbacks

Use the following link to trackback from your own site:
http://vault.openmonkey.com/articles/trackback/55

(leave url/email »)