I have a question about the "select" tag, if it is possible that it has a visible title without being part of the options?
I have a question about the "select" tag, if it is possible that it has a visible title without being part of the options?
You can set a select
, having a first option
checked as disabled and at the same time selected.
See:
<select>
<option disabled selected>Cars</option>
<option>Volvo</option>
<option>Mercedes Bens</option>
</select>
When you select input
, you can also remove it by using the onmounsedown
event.
See:
<select onmousedown="document.querySelector('#fake').remove()">
<option disabled selected id="fake">Cars</option>
<option>Volvo</option>
<option>Mercedes Bens</option>
</select>
Note that in this last example, I added an id in option
to make it easier to find it via querySelector
.
You can also define as in the first example, however adding a display:none
to the first option
.
<select>
<option disabled selected style="display: none">Cars</option>
<option>Volvo</option>
<option>Mercedes Bens</option>
</select>
In the latter example, I recommend using required
in your select
. There, the other option
would have to have some value in value
, leaving only the first with nothing in value
.
See:
<form>
<select required>
<option disabled selected style="display: none;" value="">Cars</option>
<option value="volvo">Volvo</option>
<option value="mercedes">Mercedes Bens</option>
</select>
<button type="submit">Submit</button>
</form>
Note : If you want to set a CSS for the first option
to differentiate from others, it is possible. But in the tests I did it only worked when you clicked select
(and I do not know if it works in other browsers).
Tested on Google Chrome:
<select required>
<option selected style="color: #555; background-color: #ddd">Cars</option>
<option value="volvo">Volvo</option>
<option value="mercedes">Mercedes Bens</option>
</select>
<select>
<optgroup label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
Source: W3schools