Yogzzz
Yogzzz

Reputation: 2785

Rails select tag selected value

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.

Upvotes: 19

Views: 35715

Answers (3)

Gabriel Lucuy
Gabriel Lucuy

Reputation: 300

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.

Upvotes: 1

Jonathan MacDonald
Jonathan MacDonald

Reputation: 875

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

Upvotes: 10

gabrielhilal
gabrielhilal

Reputation: 10769

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 )) %>

Upvotes: 28

Related Questions