Is there a way in javascript/jquery or css to make html <select>/@Html.DropDownList
auto width so it fits currently selected item, I tried with diplay:inline-block
and width:auto
but width always seems to fit largest item on list?
My answer is similar to D3mon-1stVFW's, but instead uses a hidden drop-down to set the width on dynamically. As long as you use the same styling for your hidden and "real" one, it should account for different font sizes, decoration, etc. Here's the HTML:
<!-- this is our hidden "template" drop-down that we'll
use to determine the size of our "real" one -->
<select id="template" style="display:none;">
<option id="templateOption"></option>
</select>
<!-- this is our "real" template that will be re-sized -->
<select id="sel">
<option>Short</option>
<option>Really, Really, Really Long</option>
</select>
And the Javascript:
function setSelectWidth() {
var sel = $('#sel');
$('#templateOption').text( sel.val() );
// for some reason, a small fudge factor is needed
// so that the text doesn't become clipped
sel.width( $('#template').width() * 1.03 );
}
$(document).ready( function() {
setSelectWidth();
$('#sel').change( function() {
setSelectWidth();
} );
});
JSFiddle here: http://jsfiddle.net/kn9DF/1/
Variation on @Ethan Brown's answer, with the .val()
corrected to .text()
and a dynamically-created select
so your page isn't polluted:
HTML:
<select id="sel">
<option>Short</option>
<option>Really, Really, Really Long</option>
</select>
JS:
function setSelectWidth(selector) {
var sel = $(selector);
var tempSel = $("<select style='display:none'>")
.append($("<option>").text(sel.find("option:selected").text()));
tempSel.appendTo($("body"));
sel.width(tempSel.width());
tempSel.remove();
}
$(function() {
setSelectWidth("#sel");
$("#sel").on("change", function() {
setSelectWidth($(this));
});
});
Fiddle:
http://jsfiddle.net/kn9DF/242/
Tested on Chrome 39, FF 36, IE 11.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With