Explain Codes LogoExplain Codes Logo

Blank HTML SELECT without blank item in dropdown list

html
responsive-design
css
javascript
Anton ShumikhinbyAnton Shumikhin·Oct 23, 2024
TLDR

Clear that SELECT dropdown of any blank option by applying a hidden and disabled placeholder option:

<select> <option value="" hidden disabled selected></option> <option>Option 1</option> <option>Option 2</option> </select>

This code gives the dropdown a blank-free start with a non-selectable default option.

Time for some style: CSS

For legacy browsers, you can eliminate the default blank space using CSS applied directly to the option element:

option[hidden] { display: none; /* "Now you see me, now you don't!" */ }

This slick CSS rule ensures that the blank option stays hidden, even if the hidden attribute proves ineffective.

When style isn’t enough: JavaScript

For specific interactions or when CSS doesn't cut it, let JavaScript step in. Gain more control over your options:

// "Size does matter!" - Oversized index values are no longer threatening. window.onload = function() { document.querySelector('select').selectedIndex = -1; }

This snippet sets the selected index when the page loads, displaying a non-blank option to the user right from the start.

Going the extra mile with jQuery

For jQuery lovers, handling selection state can be made even simpler:

// "Who says you can't teach an old dropdown new tricks?" $(document).ready(function() { $('select').val($('select option:eq(1)').val()); });

The above jQuery code sets the default selection to the first non-blank option in a jiffy.

Breaking the ice: User engagement

Enhance user interactions by embedding a subtle prompt within the option tag:

<select> <option value="" hidden disabled selected>Pick one... Any one!</option> <!-- "Choices, choices..." --> ... </select>

This simple prompt helps guide users without introducing an unwanted blank space.

Dynamic selection: Tailored UX

For dynamic web applications, select a default option based on user preference or data:

// "The early bird catches the first option!" window.onload = function() { const userPreference = 'potato'; // insert fetch or calculation here document.querySelector('select').value = userPreference; }

This snippet improves the user experience by pre-selecting a relevant option.

Testing and validation: Covering all bases

Testing the behavior of dropdown lists is crucial for a clean UI. Platforms such as jsfiddle can be particularly beneficial for trialing and distributing potential solutions.

Mobile-first considerations

Mobile devices can be a bit quirky at times. Keep in mind touch interactions as well as variances across different screen sizes. You might have to perform some additional tweaks here and there.