skwidbreth
skwidbreth

Reputation: 8454

Rails select options - set first option as disabled, selected

I have a select input in my Rails form -

<%= f.select :store_type_id, @storeType.map{ |type| [type.store_type.capitalize, type.id] }, {include_blank: 'Select store type'} %>

How can I make it so that the first option ('Select store type') is both disabled and selected?

The html equivalent that I'm going for would be

<option disabled selected>Select store type</option>

Thank you!

Upvotes: 6

Views: 6420

Answers (2)

deepak raghuwanshi
deepak raghuwanshi

Reputation: 144

You can use disabled and pass the options to do disabled

<%= f.select :field_name, options, {disabled: ['disabled_option_1', 'disabled_option_2']}, {id: "Select"} %>

Upvotes: 4

Josh Brody
Josh Brody

Reputation: 5363

There's no way of doing this (natively) that will ensure cross-browser functionality, but here's an answer:

# on store types 
def self.options
  options = self.all.collect { |type| [type.capitalize, type.id] } 
  options.unshift(["Select Store Type", "0"])
  options
end 

# in your form 
<%= f.select :store_type_id, options_for_select(StoreType.options, :disabled => "0") %> 

However, you're depending on the browser to select a disabled input, which will contradict itself. Chrome latest goes to the next non-disabled input.

Instead, you may want to do some form validation to ensure that the value of the select is not blank.

And to keep future Ruby developers happy (and to keep yourself in line with conventions and best practices), keep in mind that Ruby endorses snake_casing your variables :)

Upvotes: 4

Related Questions