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.

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? Commented Mar 6, 2013 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. Commented Mar 6, 2013 at 17:00

3 Answers 3

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 )) %>
Sign up to request clarification or add additional context in comments.

1 Comment

How does that specify which value is selected?
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.