The best way to show default text in an HTML select
dropdown is by using a combination of selected
, disabled
and hidden
attributes on the select
option
that has the default text. The following table shows how each of these attributes affect the behavior of the select
dropdown:
Attribute | Description |
---|---|
selected |
Makes the option selected by default. |
disabled |
Makes the option unusable. |
hidden |
Hides the option when dropdown list is visible. |
All three attributes have great browser support in new and old browsers. Bear in mind though that for IE, the hidden
property is supported from v11.
Hide Default Text When select
Dropdown Is Visible
To show default select
option
text on page load (and when no other dropdown option
is selected), we can do the following:
<select> <option selected disabled hidden>Choose a Color</option> <option value="blue">Blue</option> <option value="pink">Pink</option> </select>
As soon as you click on the select
dropdown, it will hide "Choose a color" from the list of options that show. Once another option
is selected, the default option
will no longer show or be selectable.
Live Demo:
Show Disabled Default Text When select
Dropdown Is Visible
To show the default text option
even when the dropdown options are visible (after clicking on the select
list), simply use the selected
and disabled
attributes (without the hidden
attribute), like so:
<select> <option selected disabled>Choose a Color</option> <option value="blue">Blue</option> <option value="pink">Pink</option> </select>
This would keep the option "Choose a Color" visible by default till another option
is selected, and also when all dropdown options are visible after the select
list is clicked on.
Live Demo:
Re-Selectable Default select
Text
To make the default text option
re-selectable (i.e. even after another option
was selected) we can use the selected
attribute on its own (without disabled
and/or hidden
). For example:
<select> <option selected>Choose a Color</option> <option value="blue">Blue</option> <option value="pink">Pink</option> </select>
Live Demo:
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.