instance method options_for_select

Ruby on Rails 2.2.3

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

options_for_select(container, selected = nil)

Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container where the elements respond to first and last (such as a two-element array), the “lasts” serve as option values and the “firsts” as option text. Hashes are turned into this form automatically, so the keys become “firsts” and values become lasts. If selected is specified, the matching “last” or element will get the selected option-tag. selected may also be an array of values to be selected when using a multiple select.

Examples (call, result):

options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
  <option value="$">Dollar</option>\n<option value="DKK">Kroner</option>

options_for_select([ "VISA", "MasterCard" ], "MasterCard")
  <option>VISA</option>\n<option selected="selected">MasterCard</option>

options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
  <option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option>

options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
  <option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option>

NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.

Parameters

container req
selected opt = nil
Source
# File actionpack/lib/action_view/helpers/form_options_helper.rb, line 190
      def options_for_select(container, selected = nil)
        container = container.to_a if Hash === container

        options_for_select = container.inject([]) do |options, element|
          text, value = option_text_and_value(element)
          selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
          options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}>#{html_escape(text.to_s)}</option>)
        end

        options_for_select.join("\n")
      end

Defined in actionpack/lib/action_view/helpers/form_options_helper.rb line 190 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::FormOptionsHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close