Reputation: 52917
The answers to how do I use a default placeholder ... in a select_tag? show how to set a default value for the select field.
<%= f.select :country, countries, {include_blank: true, prompt: "United States"}, {required: true, class: "form-control"} %>
The problem here is that I only want the silhouette of the placeholder, not an actual value that could accidentally be submitted.
If we compare to the placeholder
value in a text_field
, the difference is much more clear. We see the placeholder:
But we cannot accidentally submit the placeholder.
How can I get similar behaviour with the .select
field?
That is, so that there is some placeholder in the select field, but so it cannot be accidentally submitted?
Upvotes: 2
Views: 1515
Reputation: 391
Just change the boolean value of include_blank: true
to the desired placeholder string:
<%= f.select :country,
countries,
{ include_blank: "- nothing selected -" },
{ required: true, class: "form-control" }
%>
This will create a pre-selected select option with no value, which will be interpreted by Rails controllers as nil
.
Upvotes: 2
Reputation: 402
According to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select a select
has no placeholder
option. If you wish to show a predefined value that should not be submitted you can add a disabled
option to this specific item and combine it with selected
.
<%= f.select :country, [['USA', 1], ['Canada', 2]], { disabled: '1', selected: '1' } %>
Upvotes: 1