Textfield_with_auto_complete - filling two fields


#1

I am going nuts here…

I have a form where users can write a city name (used with
auto_complete) - and once they click on the desired city in the dropdown
menu - I would like to have the Country field filled automatically as
well…

Is this possible at all ?
If so, can somebody please tell me where I can find some documentation
on the subject, or preferrably an example ?

Many thanks in advance,

/mich


#2

I’ve been trying to do this too. What I have found
http://rubyonrails.org/api/classes/ActionView/Helpers/JavaScriptMacrosHelper.html
it looks like you might need auto_complete_field. I haven’t had time
to work with it but it looks like you can call a JS function after a
selection is made.( :after_update_element:)
I don’t think that function works with text_field_with_auto_complete.

hth

john.
if you get it to work let me know.


#3

mich wrote:

In my view:
<%= text_field_with_auto_complete :project, :code, {},
:after_update_element =>
“function (field, element) {
var my_array = field.value.split(’-’);
field.value = my_array[0];
document.getElementById(‘project_client_name’).value =
my_array[1];
}” %>

Actually, I had to add some code to remove newlines (\n) as it was added
to each field, it looks like this now:

<%= text_field_with_auto_complete :project, :code, {},
:after_update_element =>
“function (field, element) {
var my_array = field.value.split(’-’);
field.value = my_array[0];
field.value = field.value.replace(/^\s*|\s*$/g, ‘’);
field.value = field.value.replace(/\n/, ‘’);
client_name = my_array[1].replace(/\n/, ‘’);
document.getElementById(‘project_client_name’).value =
client_name;
}”, %>

/mich


#4

John I. wrote:

I’ve been trying to do this too. What I have found
http://rubyonrails.org/api/classes/ActionView/Helpers/JavaScriptMacrosHelper.html
it looks like you might need auto_complete_field. I haven’t had time
to work with it but it looks like you can call a JS function after a
selection is made.( :after_update_element:)
I don’t think that function works with text_field_with_auto_complete.

After a whole lot of head-scratching I managed to get it work !

Here’s what I’ve got:

auto_complete template:

    <% for company in @companies do -%>
  • <%= h(company.code) %>-<%= h(company.name) %>
  • <% end %>

In my view:
<%= text_field_with_auto_complete :project, :code, {},
:after_update_element =>
“function (field, element) {
var my_array = field.value.split(’-’);
field.value = my_array[0];
document.getElementById(‘project_client_name’).value =
my_array[1];
}” %>

I’m using hyphen(-) as a delimiter, but you can use whatever you want.

There’s without a doubt a smarter way of doing it, but this seems to
work alright for me. I’ve tested it with firefox and opera… I’d love to
hear if it works with IE as well !

/mich