Is it possible to create a title for the "select" tag without it being part of the options?

1

I have a question about the "select" tag, if it is possible that it has a visible title without being part of the options?

    
asked by anonymous 19.08.2016 / 19:02

2 answers

2

You can set a select , having a first option checked as disabled and at the same time selected.

See:

Simplest way

<select>
  <option disabled selected>Cars</option>
  <option>Volvo</option>
  <option>Mercedes Bens</option>
</select>

Removing when selecting with Javascript

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 .

Removing the first item with CSS

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>

Blocking the submit if you did not select a desired option

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>
    
19.08.2016 / 19:09
0
<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

    
19.08.2016 / 19:04