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?
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>
假设您的$ country变量在Country表中具有匹配的国家/地区代码,则可以执行以下操作。
select_tag "currency", options_from_collection_for_select(Country.all, "country_code", "currency_name", $country)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.