How to expand 'select' option width after the user wants to select an option
Very old question but here's the solution. Here you have a working snippet using jquery
. It makes use of a temporary auxiliary select
into which the selected option from the main select is copied, such that one can assess the true width which the main select
should have.
$('select').change(function(){
var text = $(this).find('option:selected').text()
var $aux = $('<select/>').append($('<option/>').text(text))
$(this).after($aux)
$(this).width($aux.width())
$aux.remove()
}).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option>ABC</option>
<option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
</select>
If you have the option pre-existing in a fixed-with <select>
, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.
- You could try and set the
title
attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover. - You could use JavaScript to show the text in some positioned DIV when the user selects something. IMHO this is the not-so-nice way to do it, because it requires JavaScript on to work at all, and it works only after something has been selected - before there is a change in value no events fire for the select box.
- You don't use a select box at all, but implement its functionality using other markup and CSS. Not my favorite but I wanted to mention it.
If you are adding a long option later through JavaScript, look here: How to update HTML “select” box dynamically in IE
I fixed my problem with the following code:
<div style="width: 180px; overflow: hidden;">
<select style="width: auto;" name="abc" id="10">
<option value="-1">AAAAAAAAAAA</option>
<option value="123">123</option>
</select>
</div>
Hope it helps!