Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR - Select tag with include_blank disable

I want a result like this :

<select dir="rtl">
  <option selected disabled>Choose a car</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

With the following code I can only end up with :

<%= f.select(:car, xxxxxx, {:include_blank => 'Choose a car', :disabled => 'Choose a car'}) %>

=>

<select id="xxx" name="xxx">
  <option value="">Choose a car</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

The first option is not disabled...

like image 342
ZazOufUmI Avatar asked Jul 22 '15 15:07

ZazOufUmI


1 Answers

Ito A's answer will not work in Rails 4.2 (Unsure about earlier versions). From the documentation...

:disabled - can be a single value or an array of values that will be disabled options in the final output.

Therefore, the :disabled option should be given a value that matches the value of one of the options in the collection. So, :disabled => 'volvo' would disable the option with value='volvo'. However, it will not match the include_blank option, because that option is not part of the collection passed into the select method.

Rails select helper does not directly support the desired behavior. However, you can work around it by adding a blank option to the collection as follows.

Create the collection and then add a blank option to it.

car_names = %w(volvo saab mercedes audi)
car_names_with_blank = car_names.map{|c| [c, c]}.prepend(['Choose a car', nil])

In the view:

<%= f.select(:name, car_names_with_blank, {disabled: '', selected: ''}) %>

Here's a link to a Github repository with a working example. The example also shows that Ito A's answer and other answers to similar SO questions will not work.

UPDATED: I Have updated my answer with a solution and additional info.

like image 152
Joe H Avatar answered Nov 15 '22 22:11

Joe H