Disable first nil option - rails

330 Views Asked by At

Wondering if there is a way to disable only the first nil option in a list of options. There are multiple options with nil values.

For example if we have

options_for_select(
[["first", nil], 
["second", "second"],
["third", "third"],
["fourth", nil]])

It generates

<option name="first" value>first</option>
<option name="second" value="second">Second</option>
<option name="third" value="third">Third</option>
<option name="fourth" value>Fourth</option>

and passing in the disabled values will disable all values with nil

options_for_select(
[["first", nil], 
["second", "second"],
["third", "third"],
["fourth", nil]] , :disabled=>"")

<option name="first" value disabled>first</option>
<option name="second" value="second">Second</option>
<option name="third" value="third">Third</option>
<option name="fourth" value disabled>Fourth</option>

Anyway I can specify one the first option to be disabled regardless of value? The end goal is to have

<option name="first" value disabled>first</option>
<option name="second" value="second">Second</option>
<option name="third" value="third">Third</option>
<option name="fourth" value>Fourth</option>
2

There are 2 best solutions below

0
Pardeep Saini On

you can update your values and pass to option_for_select helper.

arr = [["first", nil],["second", "second"],["third", "third"],["fourth", nil]]

val = arr.select{|v| v[1].nil?}
if val.any?
  dis = val[0][0]
  arr.push(:disable=>dis)
end

In above example first of all i select all the nil value from the array and then i select the first nil value and pass that value to the disable variable. Now you can pass the arr variable to the helper

options_for_select(arr)

Hope this works for you.

0
seph On

Since you're using the 2d array form the only option is to key on the second element. Let's use a hash instead:

hsh = {
  "first" => nil,
  "second" => "second",
  "third" => "third",
  "fourth" => nil
}

find the key of the 1st nil:

key = hsh.find { |_, v| v.nil? }[0]

mark that entry:

hsh[key] = :disable_this_one

and generate the array:

hsh.to_a.push :disabled => :disable_this_one
=> [["first", :disable_this_one], ["second", "second"], ["third", "third"], ["fourth", nil], {:disabled=>:disable_this_one}] 

Not tested so there might be some surprises.