stevec
stevec

Reputation: 52917

Placeholder in form_for select field?

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.

For example: enter image description here

enter image description here

<%= 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:

enter image description here

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

Answers (2)

Andreas Gebhard
Andreas Gebhard

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

HJW
HJW

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

Related Questions