Using RJS before a form element is changed

As mentioned in a previous thread, I'm testing RJS templates to see if they can help me meet some requirements for a project I'm about to start.

The goal is to generate forms that use AJAX to help the user understand what can be entered. In many cases, our forms have rules like "If Option A is selected then Text Field C can not be used."

So I put together a small test form with two text inputs and a radio- button set: one button labeled Yes and one button labeled No.

The requirements I'm trying to test are:

    * When Yes is clicked, hide Element 2     * When No is clicked, display Element 2     * If an element is hidden, its label is hidden     * When form is first rendered for editing, Element 2 is hidden if Yes is already selected.

I've gotten the first three down, but can't get number four.

Currently I'm using form_observer to watch for changes to my little form. And if those changes require an element to be hidden or shown, code in the RJS view file is handling that. But form_observer only fires when the form changes, not when it is first loaded.

I could write code in the _form partial to hide those fields when it's first building the form, but that's not very DRY. I'd have the element- hiding rules in both the _form partial and the RJS template.

I tried adding ":on => 'load'" to the form_observer, but that did not work. Also, creating a "periodically_call_remote" didn't seem to do what I wanted, either.

Any ideas?

Thanks for pitching in with all my recent questions.

Ian

They are indeed client-side and I can write plain javascript to achieve my needs. But my hope is that I can avoid doing that & simply stick to writing ruby. If it turns out I can't then at least I tried.

Disabled is probably the way I'll go, yes. But in this iteration I'm using hide.

In case anyone else is looking to do the same thing, I'll document my solution.

With Prototype 1.6.0, you can create a document observer. It's a nice way to perform an action when the page is loaded. I set up my edit form to include this

<script type="text/javascript"> //<![CDATA[ document.observe('dom:loaded', function() {new Ajax.Request('/people/ dynamics/<%= @person.id.to_s %>', {asynchronous:true, evalScripts:true, parameters: $('<%= "edit_person_" + @person.id.to_s %>').serialize(false) + '&authenticity_token=' + encodeURIComponent('< %= form_authenticity_token %>')})}) //]]> </script>

So when the 'dom:loaded' event fires, a new Ajax request is created that sends the form data to my rjs template and processes the result. This way, any fields that should be hidden (or disabled) are in that state before the user starts editing the form.

Not a pretty solution, yet. But right now I just need to get the functionality working & then I can refactor it.