0

Is there any way to make the width of the option change according to what's being displayed so that the select arrow isn't so far when someone picks one of the shorter options?

<select>
  <option value="all">Choose one</option>
  <option value="1">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</option>
  <option value="2">bbbbbbbbbbbbbbb</option>
  <option value="3">cccc</option>
  <option value="4">ddd</option>
  <option value="5">ee</option>
  <option value="6">f</option>
</select>
0stone0
  • 34,288
  • 4
  • 39
  • 64
illyria
  • 324
  • 4
  • 19

1 Answers1

1

Transforming a jquery answer to vanilla js, you need sth like this

function changeWidth() {
  let ghostSelect = document.createElement('select');
  const select = document.getElementById('select');
  var x = select.options[select.selectedIndex].text;
  
  const ghostOption = document.createElement("option");
  ghostOption.setAttribute("value", x);
  var t = document.createTextNode(x);
  ghostOption.appendChild(t);
  ghostSelect.appendChild(ghostOption);
  window.document.body.appendChild(ghostSelect)
  select.style.width = ghostSelect.offsetWidth + 'px';
    window.document.body.removeChild(ghostSelect)
}
    <select id="select" onChange="changeWidth()">
        <option value="all">Choose one</option>
        <option value="1">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</option>
        <option value="2">bbbbbbbbbbbbbbb</option>
        <option value="3">cccc</option>
        <option value="4">ddd</option>
        <option value="5">ee</option>
        <option value="6">f</option>
    </select>

So what it actually does is that it creates a dummy select with only the selected option, adds it temporarily to the DOM, then calculates the width, sets the original's select width to the new width and then it removes the dummy select from the DOM.

Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • 1
    It's worth noting that any differnces in the styles of the original `select` and the "ghost" `select` may result in inconsistent results. So make sure to apply the same classes to the ghost element and/or append to the same location as the original (depending on your styling selectors, different approaches may be needed) – DBS Apr 20 '22 at 09:13
  • of course. the sample was as simple as the original `select` in the post! – Apostolos Apr 20 '22 at 09:15
  • 1
    You can better post this on the marked duplicate so that can be used as a refference. – 0stone0 Apr 20 '22 at 09:16