3

I have large list of the drop-down menu. Some of the option have very large text. and I want to make the width of the selected element as per the selected option.

If the selected option is "Selected" then width should be like 120px or something. When user select "Very Large Selected option" then widht of the <select> tag should be increase.

Here is the sample code, what I am trying to do. http://jsbin.com/axaka4/edit

roryf
  • 29,592
  • 16
  • 81
  • 103
Wasim Shaikh
  • 6,880
  • 18
  • 61
  • 88
  • See also http://stackoverflow.com/questions/20091481/auto-resizing-the-select-element-according-to-selected-options-width – rogerdpack Apr 21 '17 at 19:17

2 Answers2

13

Using some cheating you could clone content of the selected option, measure it's width and resize select to this width like this:

$('select').change(function(){
    var $opt = $(this).find("option:selected");
    var $span = $('<span>').addClass('tester').text($opt.text());

    $span.css({
        'font-family' : $opt.css('font-family'),
        'font-style' : $opt.css('font-style'),
        'font-weight' : $opt.css('font-weight'),
        'font-size' : $opt.css('font-size')
    });

    $('body').append($span);
    // The 30px is for select open icon - it may vary a little per-browser
    $(this).width($span.width()+30);
    $span.remove();
});

$('select').change();

A working fiddle here

mkilmanas
  • 3,395
  • 17
  • 27
  • Or add a temporary select and measure that instead? http://stackoverflow.com/questions/6385533/how-to-change-width-of-the-select-element-as-per-the-selected-option/6385741#6385741 – rogerdpack Apr 21 '17 at 21:23
-1

i have not tested it but i think this should work.i am assuming you have multiselect dropdown

 $("selectId").change(function () { 
         $("selectid option:selected").each(function () { 
                str = $(this).width(); 
                $('#selectId').width(str); 
          }); 
});
Vivek
  • 10,978
  • 14
  • 48
  • 66
  • Unfortunately it appears that select options' "width" is always zero so you can't do it, nor use getBoundingRect. Dang HTML! – rogerdpack Apr 21 '17 at 19:16