javascripthtmlrazor-pages

When <Option> is chosen only display partial value of in <Select> - HTML


I have a SELECT that is pulling in 2 db fields (TYPE and DESCRIPTION) to form the displayed OPTION values (option example: ft - full-time, pt - part time, sl - seasonal, etc.).
When the drop-down options are displayed, I want to see both TYPE and DESCRIPTION (as detailed in my example) but I only want the TYPE displayed on the form/page after it is selected.

<label>Employee Type</label>
<select>
  <Option value="" disabled selected hidden>--Select Type--</Option>
  @if (Model.DropDownItems != null) {
    @foreach (var item in Model.DropDownItems) {
      <option value="@item.Type">@item.Type - @item.Desc</option>
    }
  }
  else {
    <option value="" disabled>No data available</option>
  }
</select>

Solution

  • You can customize the select using CSS to get the requested result:

    select,
    ::picker(select) {
      appearance: base-select;
    }
    
    option {
      &::after {
        content:" - "attr(data-desc);
      }
    }
    <label>Employee Type</label>
    <select>
      <button>
        <selectedcontent></selectedcontent>
      </button>
      <option value="" disabled selected hidden>--Select Type--</option>
      <option value="ft" data-desc="full-time">ft</option>
      <option value="pt" data-desc="part time">pt</option>
      <option value="sl" data-desc="seasonal">sl</option>
    </select>