Make multiple-select to adjust its height to fit options without scroll bar

前端 未结 16 991
说谎
说谎 2020-12-24 03:59

Apparently this doesn\'t work:

   select[multiple]{
     height: 100%;
   }

it makes the select have 100% page height...

auto

相关标签:
16条回答
  • 2020-12-24 04:37

    I guess you can use the size attribute. It works in all recent browsers.

    <select name="courses" multiple="multiple" size="30" style="height: 100%;">
    
    0 讨论(0)
  • 2020-12-24 04:37

    To adjust the size (height) of all multiple selects to the number of options, use jQuery:

    $('select[multiple = multiple]').each(function() {
        $(this).attr('size', $(this).find('option').length)
    })
    
    0 讨论(0)
  • 2020-12-24 04:37

    You can count option tag first, and then set the count for size attribute. For example, in PHP you can count the array and then use a foreach loop for the array.

    <?php $count = count($array); ?>
    <select size="<?php echo $count; ?>" style="height:100%;">
    <?php foreach ($array as $item){ ?>
        <option value="valueItem">Name Item</option>
    <?php } ?>
    </select>
    
    0 讨论(0)
  • 2020-12-24 04:39

    Here is a sample package usage, which is quite popular in Laravel community:

    {!! Form::select('subdomains[]', $subdomains, null, [
        'id' => 'subdomains',
        'multiple' => true,
        'size' => $subdomains->count(),
        'class' => 'col-12 col-md-4 form-control '.($errors->has('subdomains') ? 'is-invalid' : ''),
    ]) !!}
    

    Package: https://laravelcollective.com/

    0 讨论(0)
  • 2020-12-24 04:42

    I had this requirement recently and used other posts from this question to create this script:

    $("select[multiple]").each(function() {
      $(this).css("height","100%")
        .attr("size",this.length);
    })
    
    0 讨论(0)
  • 2020-12-24 04:47

    Using the size attribute is the most practical solution, however there are quirks when it is applied to select elements with only two or three options.

    • Setting the size attribute value to "0" or "1" will mostly render a default select element (dropdown).
    • Setting the size attribute to a value greater than "1" will mostly render a selection list with a height capable of displaying at least four items. This also applies to lists with only two or three items, leading to unintended white-space.

    Simple JavaScript can be used to set the size attribute to the correct value automatically, e.g. see this fiddle.

    $(function() {
        $("#autoheight").attr("size", parseInt($("#autoheight option").length)); 
    });
    

    As mentioned above, this solution does not solve the issue when there are only two or three options.

    0 讨论(0)
提交回复
热议问题