I am trying to have a <select>
be required in my Rails form.
This is my code (elipsis is to make line shorter):
<div class="field">
<p><%= f.label :category, "Category:" %></p>
<%= f.select :category, ['Analytics','Commerce',..., 'Web'], :prompt => '-- Select One --', :required => true %>
</div>
Which outputs
<div class="field">
<p><label for="startup_category">Category:</label></p>
<select id="startup_category" name="startup[category]">
<option value="">-- Select One --</option>
<option value="Analytics">Analytics</option>
<option value="Commerce">Commerce</option>
<option value="Content Management">Content Management</option>
<option value="Gaming">Gaming</option>
<option value="Green">Green</option>
<option value="Media">Media</option>
<option value="Social Media">Social Media</option>
<option value="Technology - Software">Technology - Software</option>
<option value="Technology - Hardware">Technology - Hardware</option>
<option value="Web">Web</option></select>
</div>
Putting {:required => true}
instead of :required => true
gives a syntax error and {:prompt => '-- Select One --', :required => true}
renders the page, but without the required="true"
in my select tag.
How can I get required="true"
in my tag?
try this one....
f.select :category, ['Analytics','Commerce',..., 'Web'], { :include_blank => '-- Select One --' }, :required => true
For Rails 4
f.select :category,
['Analytics','Commerce',..., 'Web'],
{
include_blank: '-- Select One --' ,
required: true
}
I am not sure if it accomplish what you want, but I have two solutions for you. You can use simpleform gem.
OR
Style it:
<label class="required">Category</label>
The in css:
label.required:after{content:"*"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With