Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the default selected item in a Rails drop-down menu?

When creating a standard Rails dropdown menu how do you set which item in the list should be default?
I ask because in the past I've been just putting a nil entry as the first item in my list of values that are going into the drop-down, but when using {:include_blank => true} the blank entry is not the default selected item, the first item from the list is.

like image 764
keybored Avatar asked Feb 02 '11 21:02

keybored


People also ask

How do I change the default value in a drop down box?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How to get the selected value in a dropdown?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How to know which option is selected in dropdown?

You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How to display the selected value in dropdown in js?

STEP 1 − Create a select tag with multiple options and assign an id to the select tag. STEP 2 − Also, create an empty DOM with an id to display the output. STEP 3 − Let there be a button element for the user to click and see the option selected. STEP 4 − Let the user select an option from the dropdown list.


2 Answers

You have many options to populate <select> tag with <option> tags, one of them is options_for_select(container, selected = nil) which takes a selected param which should be the value of your <option> field you want to be selected by default.

like image 20
Mirko Avatar answered Sep 28 '22 07:09

Mirko


You can use :selected

<%= f.select :title, ['1','2','3','4'], :selected => '3' %>
like image 70
fl00r Avatar answered Sep 28 '22 08:09

fl00r