19

My tag:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5], :selected => :option ])) %>

How do I set the selected value to which option is selected. For example, if I select ['Bought', 3], and submit, ['All', 1] option is selected. How can I display the selected value after the form is submitted.

Yogzzz
  • 2,735
  • 5
  • 36
  • 56
  • If you select `['Bought', 3]` in the browser and then submit, where are you seeing that `['All', 1]` was selected? Can you show the rest of the form as well as the controller code relevant for the form action? – PinnyM Mar 06 '13 at 16:47
  • The options are closed ( `]` ) in the wrong place, so the browser see `:selected => :option` as one option. Fixing the problem, you can refresh the browser and the selected option will remain selected. – gabrielhilal Mar 06 '13 at 17:00

3 Answers3

28

You did everything right, just close the options ] before the :selected => :option:

instead of ...], selected: :option ])), change to ...]], selected: :option ))

So, your code should be:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5]], selected: :option )) %>
gabrielhilal
  • 10,660
  • 6
  • 54
  • 81
10

Try this:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5]], :selected => params[:option])) %>

This works perfectly in rails 4.2

Hass
  • 1,628
  • 1
  • 18
  • 31
1

In case you want to add a class to the tag:

<%= select_tag(:option, options_for_select([["Option 1",1],["Option 2",2],["Option 3",3]], params[:option] ), class:"select") %>

Worrking in rails 5.

Gabriel Lucuy
  • 300
  • 3
  • 9