devroom.io/drafts/2007-02-21-ror-link_to_remote-with-a-text_field-value-as-an-argument.md
Ariejan de Vroom dbae98c4c0 Moar updates
2013-03-24 14:27:51 +01:00

2.6 KiB

title kind slug created_at tags
RoR: link_to_remote with a text_field value as an argument article ror-link_to_remote-with-a-text_field-value-as-an-argument 2007-02-21
General
RubyOnRails
Features

Forms are very well supported in Ruby on Rails. But in some cases you want to get information about a value a user has entered in a form, but without submitting the entire form. A good example of this is the sign up procedure at Yahoo. You enter your desired username, click "check availability" and you know if the name is available to you.

In my case I want to add locations to my database and use geocoding to get latituden/longitude values. So, I want users to enter an address and click "check" to verify that geocoding is successful. When successful, the full address and lat/lng values are automatically filled out in the form.

This article shows you how to update those text fields and most importantly, it shows how to add a text_field value as a paramater to your link_to_remote tag.

This last part is easy with RJS:

render :update do |page|
  page[:location_address].value = gecode.full_address
  page[:location_lat].value = geocode.lat
  page[:location_lng].value = geocode.lng
end

But now the tricky part! How to include the value of a text_field in a link_to_remote tag?? A normal link_to_remote tag might look like this:

link_to_remote "Check address",
   :url {
      :controller => 'locations',
      :action => 'check_address',
      :address => @location.address
   },
   :method => :get

The problem here is that we're at the 'new' form, so @location doesn't contain anything yet. Erb isn't going to help us either because it's already rendered and cannot change something 'onClick'.

You got it, JavaScript is your friend! You could now write a JS function that retrieves the value of the text_field and add it to the link_to_remote request. Well, you could. But there is an easier way!

Prototype is the answer! It comes default with Rails and if you already use the javascript defaults, it's already at your diposal. If not, include prototype in your layout first:

< %= javascript_include_tag 'prototype' %>

Now, we can use Form.element.getValue to get the text_field value. Since Prototype is very nice, there's a shortcut available: $F(element).

The next question is how to integrate this with our link_to_remote tag. The :with paramater offers help!

link_to_remote "Check address",
   :url {
      :controller => 'locations',
      :action => 'check_address',
      :address => @location.address
   },
   :with => "'address='+encodeURIComponent($F(