Flowdock
select_tag(name, option_tags = nil, options = {}) public

Creates a dropdown selection box, or if the :multiple option is set to true, a multiple choice selection box.

Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or associated records. option_tags is a string containing the option tags for the select box.

Options

  • :multiple - If set to true the selection will allow multiple choices.

  • :disabled - If set to true, the user will not be able to use this input.

  • :include_blank - If set to true, an empty option will be create

  • :prompt - Create a prompt option with blank value and the text asking user to select something

  • Any other key creates standard HTML attributes for the tag.

Examples

select_tag "people", options_from_collection_for_select(@people, "id", "name")
# <select id="people" name="people"><option value="1">David</option></select>

select_tag "people", "<option>David</option>".html_safe
# => <select id="people" name="people"><option>David</option></select>

select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>".html_safe
# => <select id="count" name="count"><option>1</option><option>2</option>
#    <option>3</option><option>4</option></select>

select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, :multiple => true
# => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
#    <option>Green</option><option>Blue</option></select>

select_tag "locations", "<option>Home</option><option selected="selected">Work</option><option>Out</option>".html_safe
# => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option>
#    <option>Out</option></select>

select_tag "access", "<option>Read</option><option>Write</option>".html_safe, :multiple => true, :class => 'form_input'
# => <select class="form_input" id="access" multiple="multiple" name="access[]"><option>Read</option>
#    <option>Write</option></select>

select_tag "people", options_from_collection_for_select(@people, "id", "name"), :include_blank => true
# => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>

select_tag "people", options_from_collection_for_select(@people, "id", "name"), :prompt => "Select something"
# => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>

select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, :disabled => true
# => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
#    <option>Paris</option><option>Rome</option></select>
Show source
Register or log in to add new notes.
July 22, 2008
18 thanks

select_tag with options_for_select example

An example of using options_for_select with select_tag

select_tag 'user_id', options_for_select(@users.collect{ |u| [u.name, u.id] })

This would generate something like:

<select id="user_id" name="user_id">
  <option value="1">Brad</option>
  <option value="2">Angie</option>
  <option value="3">Jenny</option>
</select>
July 25, 2008 - (v1.0.0 - v2.1.0)
4 thanks

select_options_tag - no more worries...

no more explicit options_for_select calls..

def select_options_tag(name='',select_options={},options={})
  #set selected from value
  selected = ''
  unless options[:value].blank?
    selected = options[:value]
    options.delete(:value)
  end
  select_tag(name,options_for_select(select_options,selected),options)
end

select_options_tag(‘name’,[[‘oh’,‘no’]],:value=>‘no’)

July 23, 2008
3 thanks

options_for_select further example (using a collection and with a default value)

In this example, we are editing a collection of region records, each with its own select list of countries. (Region belongs_to :country.) If the region doesn’t have a country associated, then we want a default message of “unassigned”. Of course, if the region does have a country associated then we want that country displayed:

<% name = "region[" + region.id.to_s + "][country_id]" %>
<% id = "region_" + region.id.to_s %>

<%= select_tag(id, options_for_select([["unassigned" , "0" ]] +
                     Country.to_dropdown, region.country_id),

{:name => name} ) %> This give us:

<select id="region_3" name="region[3][country_id]">
  <option value="0">unassigned</option>
  <option selected="selected" value="12">England</option>
</select>

NB: we’re using the handy acts_as_dropdown plugin (http://delynnberry.com/projects/acts-as-dropdown/) but we could just as easily prepare the select list with map / collect as above.

August 18, 2009
2 thanks

Auto-submitting select tag

If you want your form to be submitted when user selects something, use:

:onchange => "this.form.submit();"

For example:

select_tag "people", "<option>David</option>", :onchange => "this.form.submit();"
August 26, 2009 - (v1.0.0 - v2.3.2)
1 thank

sending an array of multiple options

To make sure that you’ll receive a array you should declare the name of the select with “[ ]” like that:

Example

<%= select_tag "users[]", options_for_select(@users.collect{|x| [x.name,x.id]}), {:multiple => :multiple, :size => 10} %>
March 2, 2011 - (>= v3.0.0)
1 thank

you need use raw

in rails3

select_tag “people”, raw(“<option>David</option>”)

January 4, 2013 - (>= v3.0.0)
1 thank

Using an unobtrusive Ajax (UJS) :onchange call to the controller#action

An :onchange call can be made using the Rails 3 jquery-ujs helper in the form:

select_tag( name, option_tags, misc_html_options, html_5_data-stuff)

For example:

select_tag( "my_tag_id", get_ids(@entity), class: "progress_and_message",
  data: {
    remote: true,
    url: url_for( action: :my_controller_action, id: my_id)
    // application symbols
    progress_bar: "progress_bar_div_id",
    update: "message_div_id"
  }
)

The jquery_ujs looks for data-remote and data-url. These can be spelled out or placed in the data hash. The url must be formed as select_tag does not call url_for, unlike some of the other related tags. Values for application symbols can also be passed through. jQuery triggers will work on the Ajax events that occur. This generates the following:

<select class="progress_and_message" data-progress-bar="progress_bar_div_id" data-remote="true" data-update="message_div_id" data-url="/my_controller/my_controller_action/my_id" id="my_tag_id" name="my_tag_id"><option value=etc...></option>

For example, tying into the events in this case the program makes visible an existing hidden progress bar while awaiting a server response, and then displays a div containing a message returned by the server and hides the progress bar. If the div contains a class= for notice or error, then they will fade out.

$(".layout")
  .on('ajax:beforeSend', ".progress_and_message", function(){ 
    // get id of element to make visible
    var progress_bar_id = '#' + this.getAttribute('data-progress-bar');
    $(progress_bar_id).show();
  })
  .on('ajax:complete', ".progress_and_message", function(evt, xhr, options){ 
    // get id of element to contain message and to hide
    var update = this.getAttribute('data-update'); 
    var progress_bar_id = '#' + this.getAttribute('data-progress-bar');
    $("#" + update).replaceWith($(xhr.responseText).attr("id", update));
    $(progress_bar_id).hide();
    // cause responses with these classes to fade away...
    $('.notice').fadeOut(2500);
    $('.error').fadeOut(8000);
  });
May 2, 2009 - (v2.0.0 - v2.3.2)
0 thanks

Setting name and id for select_tag

Sometimes you need to use select_tag instead of select (because you’re after more control or need to use optgroups, for example), but still want the id/name conventions that select would give.

In this case, all you need to do is set the first parameter to whatever would be produced by select, and it’ll take care of the id and name attribute automatically, and thus ensure the form data is parsed correctly after submission.

For example, if you want to do something like:

form_for :comment do |f|
 f.select :article_id ...

which would give a select tag with id of “comment_article_id” and a name attribute of “comment[article_id]”, which be parsed into the params hash of:

'comment' => {'article_id' => ...

you can instead do

form_for :comment do |f|
 select_tag 'comment[article_id]' ...

which will give the same id and name attributes for the select tag and hence the same params hash in the controller

November 9, 2010
0 thanks

How to perform :onchange ajax call using jQuery (Rails 3)

As remote_function no longer exists in Rails 3, here is some handy substitution

<%= select_tag :assignee_id, options_for_select([["A",1],["B",2]]), 
                                :onchange => "$.post('#{model_singular_path(id)}', {'_method':'put', 'model_name[model_field]':this.value} );" %>

You can obviously pass more attributes, change method etc.

October 18, 2012
0 thanks

Showing the select with a value previously known

Enter the value in the ‘value to check if exist in the list’ section and the drop down should have that selected

Code example

select_tag "name",
options_for_select(list.collect{ [ text, value] },
            'value to check if exist in the list', 
            {:include_blank => true}