HuBeZa HuBeZa - 4 months ago 8
HTML Question

How can I display option text on the dropdown menu that is different than the selected text?

Using a simple

select
, I want to display one text on the dropdown list and another text in the select control after the option was selected. It's pretty similar to option's
label
attribute in its concept.

I'm not sure if it's even possible. Here's a not-working example:

<select>
<option select-text="-- EMPTY --"> </option>
<option select-text="YES!!!">Yes</option>
<option>No</option>
</select>





Update: I didn't mention that I need to incorporate this solution in a generated HTML (ng-table filters), so any solution that is not pure HTML will be very hard to use. I even consider to look for another table control as a simpler solution, which is pretty basic - placeholder text in select filter.

I've created a question more specific to my problem:
How can I put a placeholder text on ng-table select filter?

Answer

Here's a relatively simple solution that relies on the standard value attribute and a custom data-* attribute:

function showDisplayValue(e) {
  var options = e.target.options,
      option = e.target.selectedOptions[0],
      i;
  
  // reset options
  for (i = 0; i < options.length; ++i) {
    options[i].innerText = options[i].value;
  }
  
  // change the selected option's text to its `data-display` attribute value
  option.innerText = option.getAttribute('data-display');
}

document.getElementById('foo').addEventListener('change', showDisplayValue, false);
<select id="foo">
  <option data-display="*** BAR ***" value="Bar">Bar</option>
  <option data-display="*** BAZ ***" value="Baz">Baz</option>
  <option data-display="*** QUX ***" value="Qux">Qux</option>
</select>