Apparently this doesn\'t work:
select[multiple]{
height: 100%;
}
it makes the select have 100% page height...
auto
I guess you can use the size
attribute. It works in all recent browsers.
<select name="courses" multiple="multiple" size="30" style="height: 100%;">
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)
})
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>
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/
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);
})
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.
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.