PUBLISHED ON: JULY 29, 2021
How to add placeholder text for a Select box in HTML?
Answer: Using the disabled
and selected
attribute
The placeholder is used to display some short hint in place of the user's input before the user enters any input.
In HTML, there is a placeholder
attribute to add the placeholder to the input field and text area. But the select box does not have any placeholder
attribute.
In the case of a select box, we can add a placeholder to the select box without the placeholder attribute. In this tutorial, we will learn how to add a placeholder to a select box in HTML.
Creating Placeholder for Select Box
The first way to add a placeholder is by using the disabled
and selected
attribute. The first <option>
element is created with an empty value. This <option>
tag is disabled using a disabled
attribute and also selected by default using a selected
attribute. We will also use the hidden
attribute to hide this option while the select box is open. So when you open a select box, the first option will act as a placeholder.
Example: Placeholder for the select box
Here, we have a list of programming languages where the first option act as a placeholder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
<h2>Placeholder for select box</h2>
<select name="Program">
<option value="disabled selected hidden">Choose program</option>
<option>Find Palindrome</option>
<option>Print Fibonacci Series</option>
<option>Print a Number Pyramid</option>
<option>Reverse a String</option>
</select>
</body>
</html>
Output
Here is the output of the above program.
Using CSS display property
The second way to add a placeholder to the select box is by using the CSS display
property. Use the display:none
property to anyone <option>
tag in the select box with an empty value. Also, use the selected
attribute to select it by default.
Example: Add a placeholder to select box
When you load the page, it will display the value, but you will not be able to select it as it is hidden.
Conclusion
In this tutorial, we have learned the simplest way to add the placeholder to the check box in HTML. We can either add a disabled
and selected attribute or add display:none
property to one of the <option>
tag with empty values to make it a placeholder.