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.
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.
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.
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.
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.
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.
You can use :selected
<%= f.select :title, ['1','2','3','4'], :selected => '3' %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With