sateayam
sateayam

Reputation: 1089

how to define default selected value in select form page

I have an index.rhtml with this code

<select id="subtable" name="subtable" size="20" style="width: 400px">
      <% for haus in @hauses %> 
           <option selected value="<%= haus.id %>"><%= haus.timebuild%></option>
       <% end %>
</select>

It will show me a list of drop down files in a select box. However, everytime I refresh the page, the default selected value is always the last of the list (the bottom one). How can I make the default selected value to be the 1st one (the top one of the list), and not the last one?

Thank you

Upvotes: 0

Views: 1416

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 37507

The selected attribute is supposed to be placed on only the default-selected value, but you're putting it on all values, causing the last one to remain selected.

The simplest solution is just remove the selected attribute altogether.

You should probably use Rails view helpers, which handles this for you (and doing things like automatically default to the current attribute's value):

options_from_collection_for_select(@hauses, 'id', 'timebuild', @hauses.first.id)

Upvotes: 2

Matt
Matt

Reputation: 5398

You can use options_from_collection_for_select. Replace the for loop with this:

options_from_collection_for_select(@hauses, 'id', 'timebuild', @hauses.first.id)

Upvotes: 0

Related Questions