This project is archived and is in readonly mode.

#661 ✓stale
Arthur Carlsson

options_for_select with html_options

Reported by Arthur Carlsson | July 19th, 2008 @ 12:12 PM | in 2.x

This patch allows you to specify HTML attributes to the option elements generated by the options_for_select method and methods alike. This is useful if you want, for example, have altering backgrounds for each select option.

The html_option parameter can be a hash which applies the attributes to all option elements, like so:

options_for_select({"Dollar" => "$", "Kroner" => "DKK", "Kronor" => "SEK"}, "Kronor", :style => 'color: blue;') # => <option value="$" style="color: blue;">Dollar</option>\n<option value="DKK" style="color: blue;">Kroner</option>\n<option value="SEK" style="color: blue;">Kronor</option>

or it can be a proc to calculate the attributes for each option, like so:

options_for_select({"Dollar" => "$", "Kroner" => "DKK", "Kronor" => "SEK"}, "Kronor", lambda { |text, value, selected| {:class => cycle("odd", "even")} }) # => <option value="$" class="odd">Dollar</option>\n<option value="DKK" class="even">Kroner</option>\n<option value="SEK" class="odd">Kronor</option>

This patch also alters an existing test: test_hash_options_for_select. The expected result in the test was sorted by string comparison which does not work with the changes I made. The test's expected result is now unchanged and the result from options_for_select now expects the generated options to be sorted by its display text.

A comment has been added to the documentation about this change of expectation.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Pages