How to add a title to a html select tag

后端 未结 12 2069
长发绾君心
长发绾君心 2020-12-04 19:23

How would I go about setting a title in select tag? Here is my select box:


                        
    
提交评论

  • 2020-12-04 19:40
    <option value="" selected style="display:none">Please select one item</option>
    

    Using selected and using display: none; for hidden item in list.

    0 讨论(0)
  • 2020-12-04 19:40

    You can create dropdown title | label with selected, hidden and style for old or unsupported device.

    <select name="city" >
    <option selected hidden style="display:none">What is your city</option>
       <option value="1">Sydney</option>
       <option value="2">Melbourne</option>
       <option value="3">Cromwell</option>
       <option value="4">Queenstown</option>
    </select>
    
    0 讨论(0)
  • 2020-12-04 19:40

    Typically, I would suggest that you use the <optgroup> option, as that gives some nice styling and indenting to the element.

    The HTML element creates a grouping of options within a element. (Source: MDN Web Docs: <optgroup>.

    But, since an <optgroup> cannot be a selected value, you can make an <option selected disabled> and then stylize it with CSS so that it behaves like an <optgroup>....

    .optionGroup {
        font-weight: bold;
        font-style: italic;
    }
    <select>
        <option class="optionGroup" selected disabled>Choose one</option>
        <option value="sydney" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Sydney</option>
        <option value="melbourne" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Melbourne</option>
        <option value="cromwell" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Cromwell</option>
        <option value="queenstown" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Queenstown</option>
    </select>

    0 讨论(0)
  • 2020-12-04 19:42

    I think that this would help:

    <select name="select_1">
        <optgroup label="First optgroup category">
          <option selected="selected" value="0">Select element</option>
          <option value="2">Option 1</option>
          <option value="3">Option 2</option>
          <option value="4">Option 3</option>
        </optgroup>
        <optgroup label="Second optgroup category">
          <option value="5">Option 4</option>
          <option value="6">Option 5</option>
          <option value="7">Option 6</option>
        </optgroup>
    </select>
    
    0 讨论(0)
  • 2020-12-04 19:45
    <select>
        <option selected disabled>Choose one</option>
        <option value="sydney">Sydney</option>
        <option value="melbourne">Melbourne</option>
        <option value="cromwell">Cromwell</option>
        <option value="queenstown">Queenstown</option>
    </select>
    

    Using selected and disabled will make "Choose one" be the default selected value, but also make it impossible for the user to actually select the item, like so:

    Dropdown menu

    0 讨论(0)
  • 提交回复
    热议问题