How can I set the default value for an HTML <select>
element?
Make an <option>
pre-selected in a <select>
element by adding the selected
attribute:
In the above, "Two" will be displayed as the default choice.
Better UX with placeholders
UX can be significantly enhanced by using a placeholder as a non-selectable option. This can be done by combining disabled
, hidden
, and value=""
. Here's how you do this:
This gives users a prompt to select an option, without the danger of the placeholder being submitted by mistake.
React's way of setting default values
In React, the default value for a <select>
element is set a bit differently. This is done by using the value
attribute on the <select>
element and ensure it matches the <option>
value:
For state management in a functional component or with React Hooks, you'd use the useState
hook.
Common default pitfalls and how to fly high
Below are some typical missteps and ways to avoid them:
'selected' attribute disasters
Remember, the selected
attribute must be on the <option>
element, not the <select>
. The idea of giving the value
to the <select>
to set the default is a common misinterpretation which leads nowhere.
'Top of the list' isn't just a figure of speech
Keep your most-used options at the top of the list, just below any placeholder, it aids user interaction. For instance, if "Two" is frequently chosen:
Don't let the ghost of placeholders haunt your form submissions
A disabled placeholder ensures it doesn't get submitted as a form value because browsers ignore disabled <option>
contained within <select>
.
Advanced practices and helper birds
To improve the user's journey of defaults, consider these:
Priority and accessibility: Elevating UX
For accessibility, it's beneficial to direct the focus to major options. Prioritization helps.
Cross-browser and cross-device consistency
Ensure that your default choices display well across devices by conducting extensive testing on various screen sizes.
Cleanup after selection
Consider hiding the placeholder post a valid selection to maintain a clean UI. This can be done using JavaScript and by adding a CSS class which sets display: none
on the chosen placeholder.
Was this article helpful?