Juan Velez
Juan Velez

Reputation: 741

Make "selected" value not visible in html select/dropdown list

I was wondering if it is possible to make the current "selected" value not be visible in my html dropdown list.

For example if I have the following:

<select>
  <option value="volvo">Volvo</option>
  <option value="saab" selected>Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

then my dropdown list will have the 4 different options with the 2nd option "Saab" being the selected value.

As is, when the user clicks on the dropdown arrow they will see Saab as the selected value at the top and then see all 4 options with Saab being listed again.

Is it possible to make it so that when they click the dropdown list they will only see Saab once (as the selected value) and then the other 3 options that are not currently selected, instead of showing Saab twice?

Upvotes: 0

Views: 12864

Answers (2)

dfsq
dfsq

Reputation: 193261

You can achieve it with this CSS styles:

option:checked {
    display: none;
}
<select>
    <option value="volvo">Volvo</option>
    <option value="saab" selected>Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>

However, user experience may become confusing, so think twice if you really need this behavior.

:checked pseudo class is supported in IE9+.

Upvotes: 3

Runcorn
Runcorn

Reputation: 5224

Ok you could do this using jQuery

<select id="dropDown">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>


$("#dropDown").on("change",function(){
    $(this).find("option").show();
    $("option:selected", $(this)).hide();
});

And here is the jsFiddle

Upvotes: 1

Related Questions