Explain Codes LogoExplain Codes Logo

Bootstrap select dropdown list placeholder

html
responsive-design
placeholder
selectpicker
Alex KataevbyAlex Kataev·Sep 22, 2024
TLDR

Create a Bootstrap dropdown placeholder by using a selected, disabled option with an empty value inside your select tag:

<select class="form-select"> <option value="" disabled selected>Please select...</option> <!-- More options go here --> </select>

This makes "Please select..." the default text, but it is not selectable after opening the dropdown.

More on placeholders

Make placeholder invisible in dropdown list

A placeholder can be kept hidden within the dropdown list by simply adding hidden attribute:

<select class="form-select"> <option value="" disabled selected hidden>Please select...</option> <!-- The rest of your options --> </select>

This keeps the placeholder functional but doesn't display it in the dropdown list, providing a tidier user interface.

Using jQuery for dynamic placeholders

For a more adaptive and interactable placeholder, you may incorporate jQuery:

$('#mySelect').on('change', function () { // Add a sprinkle of interactivity 🌈 if (!this.value) $(this).addClass('placeholder'); // Feeling gray... else $(this).removeClass('placeholder'); // Feeling colorful! });

The script changes the styling of the select element depending on whether an option is selected or not, by adding or removing the .placeholder class.

Customizing placeholder with selectpicker plugin

If you're using the selectpicker plugin, you can define custom text for the placeholder during initialization using noneSelectedText option:

$('.selectpicker').selectpicker({ noneSelectedText: 'Make a choice, no pressure...' });

This custom text can provide more specific guidance.

Extended placeholder functionalities

Styling your placeholder

You can style the first <option> with a lighter text color indicating it's the placeholder using custom CSS:

.form-select .placeholder { color: gray; /* Fifty Shades of Placeholder */ }

Using title attribute as alternative placeholder

In a simpler case, you may choose to use the title attribute in the option tag:

<select class="form-select"> <option title="placeholder" selected>Select an option</option> <!-- More options favored by users --> </select>

Making placeholder compatible with multi-select dropdowns

Ensure that your code practices for placeholders are compatible with both single and multi-select dropdowns:

<select class="selectpicker" multiple data-none-selected-text="No selection made"> <!-- Use the Force to select options --> </select>

Bootstrap version consideration

Different Bootstrap versions may apply different techniques, so always check the most accurate documentation.