简体   繁体   中英

How to change width of the select element as per the selected option?

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

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

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); 
          }); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM