method

options_for_select

options_for_select(container, selected = nil)
public

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>

If you wish to specify disabled option tags, set selected to be a hash, with :disabled being either a value or array of values to be disabled. In this case, you can use :selected to specify selected option tags.

Examples:

  options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => "Super Platinum")
    <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>

  options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => ["Advanced", "Super Platinum"])
    <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced" disabled="disabled">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>

  options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :selected => "Free", :disabled => "Super Platinum")
    <option value="Free" selected="selected">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>

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

1Note

HTML entities in options

Oleg ยท Apr 6, 20095 thanks

Unfortunately everything is escaped with ERB::Util#html_escape. Your only option is either manually construct options or compeletely overwrite this method.