Form Field Values and Ajax 2
In a project, I am working on, I found it necessary to read the value from one text field and update the value in another text field with Ajax without submitting the form.
Since I am using Ruby on Rails, I figured it could be done, I just had to figure out how. Here was the problem: take a value entered in to field one, perform a permutation on it and return the calculated value back into field 2. Of all the methods ROR offers to make the Ajax call, I chose the link_to_remote method, since I could link it to a little graphic. Getting the basic Ajax working was simply a matter of creating the method in the controller and returning the value. My initial code looked like this:
In the vew
<label <
span class="keyword">for="contact_customer_id
" id="show_label">Customer ID</label>
<%= text_field 'contact', 'customer_id' %></p>
<p><label for="contact_diskkey"
span> id="show_label"
;>Diskkey</label>
<%= text_field 'contact', 'diskkey' %>
<%= link_to image_tag('key.png'),
:action => 'calckey', :serial => @contact.customer_id %> In the Controller
def calckey
render :text => genkey(params[:serial])
end This worked like I anticipated returning the generated key. Ok now all I have to do is add :update => 'contact_diskkey' to the link_to_remote in the view and it will work! Wrong! :update updates the innerHtml which a text field does not have. I needed to update the value of the field.
I found the answer using an rjs template. I created an rjs template named calckey.rjs with the following line.
page << "$('contact_diskkey').value='" + @newkey + "';" calckey
@newkey = genkey(params[:serial])
render :layout => fa
lse
end And the vew
<label <
span class="keyword">for="contact_customer_id
" id="show_label">Customer ID</label>
<%= text_field 'contact', 'customer_id' %></p>
<p><label for="contact_diskkey"
span> id="show_label"
;>Diskkey</label>
<%= text_field 'contact', 'diskkey' %>
<%= link_to_remote image_tag('key.png'),
:url => {:action => 'calckey', :serial => @contact.customer_id} %> Success -- This worked at updating the disk key field. Now there was only one more step. Make it so that it read the value of the CustomerID field.
To accomplish this I used the $F function in the prototype javascript library. I change the link_to_remote function in the view to look like this:
<%= link_to_re
mote image_tag('key.png')
:url=> { :action=
>'calckey' },
:with => "'serial='+$F('contact_customer_id')" %> Viola! It works. Now the value is read from the field and not the value of the field when the page is opened.
It took much longer to figure out, than to write down. Hope it helps someone.

Your post is great! Only I think calckey.rjs should have been like this:
page[‘contact_diskkey’].value = @newkey
anyway your post helped me a lot! Thanks!
Thanks a LOT man, I have been looking for that $F function for a long time. Saved my day!