Search code examples
javascripthtmlcss

Show a different text for the selected option for `<select>`s


I want the text that's displayed in the <select> to be different from the selected <option>'s text. I have limited width to work with, so if I display all the text in the <option>, then some text with be cut off.

For example, if my markup is this:

<select>
  <option>Open (some description)</option>
  <option>Closed (a bunch of text</option>
</select>

When the first option is selected, I want to show only the word "Open" to save space. I can't just use Javascript to replace the text because if the user opens the select, then they'll see the shortened text.

Is there a way to do this using the <select> tag (i.e. without using a custom selector)?


Solution

  • Using JS, you can add a focus and blur event listeners which modify the text of the options:

    function focus() {
      [].forEach.call(this.options, function(o) {
        o.textContent = o.getAttribute('value') + ' (' + o.getAttribute('data-descr') + ')';
      });
    }
    function blur() {
      [].forEach.call(this.options, function(o) {
        console.log(o);
        o.textContent = o.getAttribute('value');
      });
    }
    [].forEach.call(document.querySelectorAll('.shortened-select'), function(s) {
      s.addEventListener('focus', focus);
      s.addEventListener('blur', blur);
      blur.call(s);
    });
    <select class="shortened-select">
      <option value="Open" data-descr="some description"></option>
      <option value="Closed" data-descr="a bunch of text"></option>
    </select>