Add a title to the SELECT tag (without the "selected disabled" option) without it appearing in the options?

2

How do I add a title to select as it appears in the options and adds when it is selected?

I know it looks like a duplicate, but the problem is that I did not find what I would like exactly, the selected disabled option works but does not deliver what I want. Using the same example I saw here in stackoverflow with selected disabled :

<select>
  <option disabled selected>- Selecione -</option>
  <option>Volvo</option>
  <option>Mercedes Bens</option>
</select>

However, what I would like to do is to have the "- Select -" title set to the placeholder property and when I was to select the field - in> the same did not appear in the options and disappeared. So:

    
asked by anonymous 03.04.2018 / 17:35

3 answers

2

You can also hide this option with some rules in CSS if you prefer.

Thinking about user experience (UX) and if the field is not mandatory in case the user changes his mind he should still have the option to uncheck the option he chose, so I believe that if the option should appear in the field!

For this I would do it this way:

select option[data-default] {
  color: #999; /* cor simulando que o campo está desabilitado depois que abre o select */
}
<select>
  <option selected data-default>- Selecione -</option>
  <option>Volvo</option>
  <option>Mercedes Bens</option>
</select>

But if you really "vanish" as the "label" here has an option merging what you did with CSS simulating a Placerholder.

select:required:invalid {
  color: gray;
}
option[value=""][disabled] {
  display: none;
}
option {
  color: black;
}
<select required>
  <option value="" disabled selected>- Selecione -</option>
  <option value="Volvo">Volvo</option>
  <option value="Mercedes">Mercedes Bens</option>
</select>

Nassa's response from Gringo StackOverflow has more information and variations. link

    
03.04.2018 / 18:07
2

I think what you want is this:

<select>
  <option selected hidden >- Selecione -</option>
  <option>Volvo</option>
  <option>Mercedes Bens</option>
</select>

To do this add "hidden" to the select option!

    
03.04.2018 / 17:50
0

I have the same effect of your image using javascript to change the text of the option that is selected and disabled.

I used css below to hide disabled options when select is expanded:

select:focus > option:disabled {display:none;}

Example:

var select = document.getElementById("teste");

select.addEventListener("click", function(){
    var options = this.options
    for(i=0;i<options.length;i++){
      if(options[i].disabled && options[i].selected )
        options[i].text="";
    }
});
select:focus > option:disabled {
  display:none;
}
<select id="teste">
  <option disabled selected>- Selecione -</option>
  <option>Volvo</option>
  <option>Mercedes Bens</option>
</select>
    
03.04.2018 / 18:19