rails
(4,470 views)

options for select with style

Here's a variant of Rails' options_for_select helper which lets you add styles to the options, such as for adding icons the the dropdown select.

The Rails' built-in options_for_select helper doesnt let you put styles in the <option> tag. Here's a replacement that does. It assumes the collection is in array format, it respects the convention that option.first is the text, and option.last is the value. We specify that the 2nd item is the style string.

Thus, our choices might look like this:

    @role_choices = [ 
['Anyone', 'padding: 2px; padding-left: 20px; background: no-repeat url(/images/world.png)', 'public'],
['Submitters', 'padding: 2px; padding-left: 20px; background: no-repeat url(/images/user_green.png)', 'submitter'],
['Screeners', 'padding: 2px; padding-left: 20px; background: no-repeat url(/images/user_go.png)', 'screener'],
['Reviewers', 'padding: 2px; padding-left: 20px; background: no-repeat url(/images/user_comment.png)', 'reviewer'],
['Managers', 'padding: 2px; padding-left: 20px; background: no-repeat url(/images/user_suit.png)', 'manager']
]

 

The view template may contain

  <%= select_tag( :role, options_for_select_with_style(@role_choices) %>

 

This can go into helpers/application_helper.rb

  def options_for_select_with_style( 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)
style = " style=\"#{element[1]}\"" if element[1] && element[1]!=value
options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}#{style}>#{html_escape(text.to_s)}</option>)
end
options_for_select.join("\n")
end

 

And you get something like this:


 

Thanks to http://technology.amis.nl/blog/?p=994 which I found on Google

 

Comments

by Giovanni on Jun 17, 2011

>>

Thanks a lot.

New Comment

markdown formatting permitted