user235195
user235195

Reputation: 347

Can I include blank field in select_tag?

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?

Upvotes: 33

Views: 28004

Answers (4)

EmFi
EmFi

Reputation: 23450

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>

Upvotes: 12

Ahmad hamza
Ahmad hamza

Reputation: 1936

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' } %>

Upvotes: 3

maro
maro

Reputation: 1506

In Rails 3 there is a :prompt option for select_tag:

select_tag "things", many_thing_as_options, :prompt => "Please select"

Upvotes: 47

schreifels
schreifels

Reputation: 431

Note that in Ruby on Rails 3, select_tag() will accept an :include_blank boolean argument (same with date_select and the like).

Upvotes: 11

Related Questions