user2728203
user2728203

Reputation:

How do I set a select box value using Rails?

I have the following select box inside my form_tag.

<select name="sel">
  <option selected=true value="+">+</option>
  <option value="-">-</option>
  <option value="*">*</option>
  <option value="/">/</option>
</select>

How do I set the option for a select box in the controller? Also, how do I retain the selected option even after submitting the form?

Upvotes: 1

Views: 612

Answers (2)

BroiSatse
BroiSatse

Reputation: 44675

<%= select_tag "sel", options_for_select([['+', '+'], ['-','-'], ['*','*'],['/','/']], params[:sel] || '*')

Upvotes: 1

Miotsu
Miotsu

Reputation: 1776

If you want to select and retain a default value, one possibility is:

<%= select_tag "sel", "<option>+</option><option selected='selected'>-</option><option>*</option><option>/</option>".html_safe %>

If you want to retain a value that was previously selected, you need to save it somewhere and make it available in your controller, say in a @previously_selected variable, then:

select_tag "whatever", options_for_select([ "+", "-", "*", "/" ], @previously_selected)

Upvotes: 0

Related Questions