Placeholder for Select Tag
Construct a unselectable placeholder within a select
tag by employing an option
designated with the disabled, selected, and hidden attributes:
This sets "Please choose your weapon" as the default unselectable prompt in your dropdown, providing users with an invitation to interact.
Make it bulletproof
Ensure the user makes an actual selection and doesn't just carry on with the placeholder. Use the required attribute on the select
tag to do this - it ensures a value is selected before form submission:
Set the value of the default option as empty and use the required attribute. It also imitates a placeholder's behaviour, can't fool us now!
Dynamic custom styling
Sometimes we want the dropdown to look different based on the selection. Bring in JavaScript to the rescue. It can aid in applying styles dynamically based on user's selection:
The script adds a new class option-selected
to the select tag when an option is selected, and this class can be styled as per requirements.
Going beyond basic HTML
For some cases, the basic HTML solution might not suffice. There's a world of libraries and frameworks that offer more sophisticated select components with additional functionalities like searchability, multiple selections, and of course, better placeholder support.
It's all an illusion
While the placeholder
attribute isn't valid for select
tags in HTML5, you know what they say - where there's a will
, there's a way
. We can replicate its effect with neat CSS tricks and data attributes:
Add your own custom data-*
attribute for easier targeting:
With this arrangement, you can control the visibility of the default option using simple CSS, based on the select
element's validity state.
Accessibility matters
Remember to make your placeholder friendly for users with disabilities. Use ARIA attributes to ensure this:
This ensures that assistive technologies convey the purpose of the select
dropdown and the non-existence of an initial value.
Was this article helpful?