Home > Net >  Show all options in select list does not work when there's only one option
Show all options in select list does not work when there's only one option

Time:11-29

I have a web page where I show list of strings (strings are fetched from API call). They are presented as select/option tags and I need to show ALL options (they should not be hidden). To make it possible I specify size attribute in select tag. Here's the code:

html:

<select size="2">
  <option value="1">1</option>
  <option value="2">2</option>
</select> 

css:

  select {
    overflow: auto;
    height: auto;
    background-color: #08112d;
    max-height: 300px;
  }
  option {
    font-size: 16px;
    color: #fff;
    padding: 1rem;
  }

enter image description here

The problem

If there's only one option in the list, then the styles are broken and select list requires a click to see options, which is something that I don't want. How to fix it?

enter image description here

P.S. I need to use select/options tags as I need their behavior (like selectable options and possibility to choose options with arrow up button ⬆ and arrow down ⬇). So I cannot use other tags (unless you can suggest how to add such behavior then).

CodePudding user response:

I can see the HTML of your broken example and it is the following:

<select size="1">
  <option value="1">1</option>
</select>

can you try the following instead:

<select size="1" multiple>
  <option value="1">1</option>
</select>

as you can see in the following docs when using multiple it sets the size to 4 elements but still since we're forcing to keep 1 it fixes the issue

CodePudding user response:

Note size="1" does not create consistent result across browsers according to mdn

If limiting the height is an option you can keep size="2" even there's a single option. And use css to set the correct display.

  select {
    overflow: auto;
    height: auto;
    background-color: #08112d;
    max-height: 300px;
    margin: 0;
    padding: 0;
    border: 0;
  }
select.single {
    overflow: hidden;
    background-color: #2d0811;
    min-width: 40px;
    max-height: 51px;
  }
option {
    font-size: 16px;
    color: #fff;
    padding: 1rem;
}
option:hover {
  background-color: #6b7081;
}
<select size="2" >
  <option value="1" >1</option>
</select>

<select size="2">
  <option value="1">1</option>
  <option value="2">2</option>
</select>

CodePudding user response:

add multiple attribute to select tag

<select size="1" multiple>
   <option value="1">1</option>
 </select>
  • Related