Postscripter
Postscripter

Reputation: 521

How to change the selected text in a drop down list in rails application based on a variable?

I have a select drop down box with a list of currencies. To make it easier for users, I want to change the default selected value in the drop down when the page loads based on the user country (will use geoip gem for that) So I will be writing this ruby code:

$country = GeoIp.geolocation(request.remote_ip, :precision => :country)

How to change the selected value of the drop down list box based on the $country value? Should I do that with Javascript? or with rails forms helper?? And what is the code for it?

Upvotes: 0

Views: 572

Answers (3)

TheAshwaniK
TheAshwaniK

Reputation: 1826

Can you try something like this:

<%= f.select :someobj, options_for_select({ "Basic" => "$20", "Plus" => "$40" }, $country ) %>

It will give you:

<select name="someobj">
 <option value="$20">Basic</option>
 <option value="$40" selected="selected">Plus</option>
</select>

Note use of Selected here.

Upvotes: 1

manishie
manishie

Reputation: 5322

Assuming that your $country variable has a matching country code in your Country table, you could do something like this.

select_tag "currency", options_from_collection_for_select(Country.all, "country_code", "currency_name", $country)

Upvotes: 1

Nick Veys
Nick Veys

Reputation: 23939

All you need to do is set the <option> element that has the country as selected='selected'. How you do that depends on how you built the option list.

For example, options_for_select takes the selected element as the 2nd argument.

options_for_select(['Alpha', 'Beta', 'Gamma'], 'Beta')
# => <option value="Alpha">Alpha</option>
# => <option value="Beta" selected="selected">Beta</option>
# => <option value="Gamma">Gamma</option>

Upvotes: 1

Related Questions