Can I include blank field in select_tag?

Viewed 26230

Is it possible to add an option like :include_blank => 'Please Select' in a method select_tag like it is possible with the select method? It seems not to work. Is there any substitute for this for select_tag method?

4 Answers

Edit: This answer is only applicable to Rails 2.

Rails 3 has improved the experience, so you do not have to use this hack. Ahmad hamza's answer directly provides the Rails 3 way of answering the question, as well as providing the more user friendly behaviour of providing a prompt.

The rest of the response remains as is for any one stuck maintaining a Rails 2 project.

Original Response

The select_tag method does not modify the options list you pass it. If you want a blank option you have to include it in your list of options.

If you're using options_for_select your list should start with the blank item, ie: ["Please select", ''].

If you're just passing html to select_tag make sure your first option is:

<option value="">Please Select</option>

By passing include_blank: true or prompt: 'Please select' as a third parameter to select_tag

<%= select_tag "individual[address][state]", options_for_select(states), { include_blank: true, class: 'form-control' } %>

For prompt, you can use like this with select_tag

<%= select_tag "individual[address][state]", options_for_select(indian_states), { prompt: 'Please select', class: 'form-control' } %>
Related