Here is an example select with four options:
<select name="cars" id="cars" >
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
and here is how it renders:
The whitespace between "Volvo" and the arrow is so that the longest option (Mercedes) will fit:
what I want is for the width of the whole selection field to be just so the selected option fits as the following examples:
I tried to set the width of the selection field to be width: fit
. I also tried using javascript to get the width of the selected option to then set the width off the selection field to be that. none of these methods worked in my case and I have not been able to find anyone who had the same issue as me online.
CodePudding user response:
Create a function to resize your input everytime a new option is selected
// resize on initial load
document.querySelectorAll("select").forEach(resizeSelect)
// delegated listener on change
document.body.addEventListener("change", (e) => {
if (e.target.matches("select")) {
resizeSelect(e.target)
}
})
function resizeSelect(sel) {
let tempOption = document.createElement('option');
tempOption.textContent = sel.selectedOptions[0].textContent;
let tempSelect = document.createElement('select');
tempSelect.style.visibility = "hidden";
tempSelect.style.position = "fixed"
tempSelect.appendChild(tempOption);
sel.after(tempSelect);
sel.style.width = `${ tempSelect.clientWidth 4}px`;
tempSelect.remove();
}
<select name="cars" id="cars" >
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>