Rails form (select/option) - how to mark selected option with HAML?

30,478

Solution 1

Something like this will work (using the older "hashrocket syntax" with the operator =>)

%select
  %option{:value => "a", :selected => params[:x] == "a"}= "a"
  %option{:value => "b", :selected => params[:x] == "b"}= "b"

Or, in newer Ruby versions (1.9 and greater):

%select
  %option{value: "a", selected: params[:x] == "a"}= "a"
  %option{value: "b", selected: params[:x] == "b"}= "b"

Solution 2

You should unleash the power of rails helpers.

For select tag:

= select_tag :param_name, options_for_select([['A data', 'A'], ['B data', 'B']], params[:param_name])

Also, instead of raw %form use form_tag or better form_for when it's possible (or more better simple_form or formtastic)

Share:
30,478
user984621
Author by

user984621

Updated on November 08, 2020

Comments

  • user984621
    user984621 over 3 years

    What's the quickest and most elegant way to mark currently selected option value in the form in HAML?

    %form{:action => '', :method => 'get'}
       %select{:name => 'param_name'}
          %option{:value => 'A'} A data
          %option{:value => 'B'} B data
    

    One way:

    - if params[:param_name] == "A"
      %option{:value => 'A', :selected => 'selected'} A data
    - else
      %option{:value => 'A'} A data
    

    but this is inappropriate when the select box will has many option fields...

  • jpganz18
    jpganz18 about 11 years
    what does the selected:params[:x] do?
  • Brett Bender
    Brett Bender over 10 years
    This answer is certainly preferable to writing raw form markup in views, if you are able to use the form helpers.
  • msanjay
    msanjay about 10 years
    the default selected value. the value for selected can be true or false (which the == evaluates to)
  • Admin
    Admin over 8 years
    love the answer would be nicer if it had an example of wrapping it in a form_tag or form_for, the HAML syntax is pretty annoying with its indentation