Rails select tag selected value
Asked Answered
P

3

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.

Plotkin answered 6/3, 2013 at 16:33 Comment(2)
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?Histogen
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.Kurman
K
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 )) %>
Kurman answered 6/3, 2013 at 16:50 Comment(1)
How does that specify which value is selected?Mutable
S
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

Sporophore answered 6/3, 2013 at 16:44 Comment(0)
E
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.

Extine answered 18/12, 2017 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.