I have a drop down where the user selects a language:
<select>
<option>English</option>
<option>Spanish</option>
</select>
- I want the default option that is initially displayed to say "Select
a language" instead of "English" (my first option, displayed by
default).
- I don't want the user to be able to select "Select a language".
If none of the options in the select have a selected
attribute, the first option will be the one selected.
In order to select a default option that is not the first, add a selected
attribute to that option:
<option selected="selected">Select a language</option>
You can read the HTML 4.01 spec regarding defaults in select element.
I suggest reading a good HTML book if you need to learn HTML basics like this - I recommend Head First HTML.
Building on Oded's answer, you could also set the default option but not make it a selectable option if it's just dummy text. For example you could do:
<option selected="selected" disabled="disabled">Select a language</option>
This would show "Select a language" before the user clicks the select box but the user wouldn't be able to select it because of the disabled attribute.
Just make option#1 Select Language:
Live Demo
<option value="" selected disabled hidden>Default Text</option>
Leaving the disabled flag in prevents them from not selecting an option and the hidden flag will remove it from the list. In my case I was using it with an enum list as well and the concept holds the same
<select asp-for="Property" asp-items="Html.GetEnumSelectList<PropertyEnum>()">
<option value="" selected disabled hidden>Select Property Enum</option>
<option value=""></option>
</select>
Put your prompt in the 1st option
and disable it:
<selection>
<option disabled selected>”Select a language”</option>
<option>English</option>
<option>Spanish</option>
</selection>
The first option will automatically be the selected default (what you see first when you look at the drop-down) but adding the selected
attribute is more clear and actually needed when the first field is a disabled field.
The disabled
attribute will make the option be un-selectable/grayed out.
Other answers suggest setting disabled=“disabled”
but that’s only necessary if you need to parse as XHTML, which is basically a more strict version of HTML. disabled
on it’s on is enough for standard HTML.
If you want to make the selection “required” (without accepting the “Select a language” option as an accepted answer):
Add the required
attribute to selection
and set the first option
’s value
to the empty string ””
.
<selection required>
<option disabled value=“”>Select a language</option>
<option>English</option>
<option>Spanish</option>
</selection>