Julien
Julien

Reputation: 185

drop down country selection for phone country code in rails

Rails noob here posing a question.

I'm trying to get users to input their phone number. Form contains separate fields for countrycode, areacode and phonenumber at the moment.

<% form_tag phones_path, :method => 'get' do %>
<th><%= text_field_tag :countrycode %></th>
<th><%= text_field_tag :areacode %></th>
<th><%= text_field_tag :search, params[:search] %></th>
<th><%= submit_tag "Search", :name => nil %></th>
<% end %>

I want to convert the countrycode field into a dropdown selection of country names, and automatically display the actual country code upon selection. Eg user selections USA, and +1 is displayed. I am going to store both the country name and the numerical code.

I think I need to use a combination of collection_select for the dropdown and javascript to refresh the display. But I'm kinda lost as to how to proceed. Will any kind soul give some hints please?

Upvotes: 1

Views: 4692

Answers (2)

sled
sled

Reputation: 14625

first you should create a hash in your controller that looks like:

@countries  = { "United States" => "+1", "Switzerland" => "+41" }

Then create a select list for the countries and add an onchange javascript event handler for the select list:

<% form_tag phones_path, :method => 'get' do %>
<th>
  <%= select_tag  :country, 
                  options_for_select(@countries), 
                  :onchange => "document.getElementById('countrycode').value = this.options[selectedIndex].value;" 
  %>
</th>
<th><%= text_field_tag :countrycode %></th>
<th><%= text_field_tag :areacode %></th>
<th><%= text_field_tag :search, params[:search] %></th>
<th><%= submit_tag "Search", :name => nil %></th>
<% end %>

Note: I've used standard Javascript for the onchange event, if you use jQuery or prototypeJS this could be written much shorter and cleaner :)

Upvotes: 2

user483040
user483040

Reputation:

You can also do this:

<%= f.collection_select(:subject_heading_source_id, SubjectHeadingSource.all, :id, :name, :prompt => "Please select...") %>

This is dependent upon having the contents of the select represented in a table somewhere and using the "form_for" approach to building your form, so it may not be entirely applicable.

EDIT: accidental-submit, sorry.

I use jQuery to find the element and update it:

$("#phones_path_country_code").attr("selected", value_of_selection)

you put this part into :onchange => "..." in the html options for the erb bit.

My jQuery is likely off but you can get a better idea at the api site. jQuery

Upvotes: 0

Related Questions