YLim
YLim

Reputation: 255

how to place the select option as the first option on the dropdown?

I added 'Select Gas' as the default value, but the problem is when I sort the @Gases variable, 'Select Gas' goes to the middle of the dropdown. I would like the 'Select Gas' to be the first item even if @Gases got sorted. How can I do this? Thank you

Gases Variable

@Gases = ['Carbon Dioxide [CO2]','Ethanol [CH3CH2OH]','Hydrogen [H2]','Hydrogen Sulfide [H2S]', 'Nitrogen Dioxide [NO2]', 'Carbon Monoxide [CO]', 'Ethene [Ethylene C2H6]', 'Other']

Search

<%= f.select :gas_analyte, @Gases, {include_blank: 'Select Gas', size:15},{class: "gas_search"} %><br>

Upvotes: 2

Views: 45

Answers (1)

calebkm
calebkm

Reputation: 1033

Although your code looks good, if you have an array and you want a particular item to always come first you can use Array#prepend to get the job done:

list = [:a, :h, :w, :c, :d, :b, :e]

list.sort.prepend(:z)
=> [:z, :a, :b, :c, :d, :e, :h, :w]

So in your case you might have:

@gases = ['Carbon Dioxide [CO2]','Ethanol [CH3CH2OH]','Hydrogen [H2]','Hydrogen Sulfide [H2S]', 'Nitrogen Dioxide [NO2]', 'Carbon Monoxide [CO]', 'Ethene [Ethylene C2H6]', 'Other']

@gases.sort.prepend('<Select Gas>')
=> ["<Select Gas>", "Carbon Dioxide [CO2]", "Carbon Monoxide [CO]", "Ethanol [CH3CH2OH]", "Ethene [Ethylene C2H6]", "Hydrogen Sulfide [H2S]", "Hydrogen [H2]", "Nitrogen Dioxide [NO2]", "Other"]

Upvotes: 1

Related Questions