tekin.co.uk

Disabled option tags in rails forms

Update: My patch has now been accepted into core, which means that as of Rails 2.3, this plugin should no longer be necessary. More details here.

Ever wanted to disable options in a form select in rails? I have; it feels more useable to me to disable out of stock product sizes:

Select with a disabled option tag greyed out and not selectable

The rails Form Option Helpers won’t let you do this as they currently stand. So until things change in core, I’ve put together the option_tags_will_disable plugin.

Simply specify the disabled values when calling options_for_select:


<%= options_for_select(
  ['Choose a size', 'small', 'medium', 'large'],
  nil,     # selected value
  'medium' # disabled value
) %>

<!-- Gives you -->

<option value="Choose a size">Please choose a size</option>
<option value="s">small</option>
<option value="m" disabled="disabled">medium</option>
<option value="l">large</option>

You can do the same when working with collections, but more interestingly, you can also give a Proc to identify which elements should be disabled:


<%= options_from_collection_for_select(
  @products,
  :id,
  :name,
  nil,
  lambda{|p| !p.in_stock? }
) %>

And as an added bonus, selected options can also be identified with a Proc!

Get more fab content like this straight to your inbox

You'll get an email whenever I have a fresh insight or tip to share. Zero spam, and you can unsubscribe whenever you like with a single click.

More articles on Ruby & Rails

Authored by Published by