Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails select_tag selected value

For the code given below I wanted to keep the select box selected with the value that is passed.

But this doesn’t work:

@yrs =[2011,2010,2009,2008]
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,:selected=>2011) %>

Please advise me how to go about it.

like image 494
lamrin Avatar asked Sep 08 '11 11:09

lamrin


3 Answers

Remove the :selected=> part.

Syntax:

options_for_select(@options, @selected_options)

Usage:

options_for_select(1..5, 3)  # creates a range 1..5 , with 3 as selected by default

Documentation

like image 51
M Tariq Aziz Avatar answered Nov 18 '22 14:11

M Tariq Aziz


<%= select_tag "page_type", options_for_select(@page_type.collect{ |u| [u.data_name, u.id]}, :selected=>@page.page_type), {:class =>"select_combobox",:onchange=>"reset_form(this.id,'page_type_msg');"} %>

this works for me :)

like image 33
manish nautiyal Avatar answered Nov 18 '22 14:11

manish nautiyal


Just to clarify @M Tariq Aziz answer:

Your code should look like this:

@yrs =[2011,2010,2009,2008]
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,2011) %>

The general format for select tag is:

<%= select_tag 'year', options_for_select(:collection, :selected) %>
like image 6
harrya Avatar answered Nov 18 '22 15:11

harrya