Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

<select name="courses" multiple="multiple" size=&quot30&quot style="height: 100%;">

You can do this using the size attribute in the select tag. Supposing you have 8 options, then you would do it like:

<select name='courses' multiple="multiple" size='8'>

Old, but this will do what you're after without need for jquery. The hidden overflow gets rid of the scrollbar, and the javascript makes it the right size.

<select multiple='multiple' id='select' style='overflow:hidden'>
<option value='foo'>foo</option>
<option value='bar'>bar</option>
<option value='abc'>abc</option>
<option value='def'>def</option>
<option value='xyz'>xyz</option>
</select>

And just a tiny amount of javascript

var select = document.getElementById('select');
select.size = select.length;

For jQuery you can try this. I always do the following and it works.

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

You can only do this in Javascript/JQuery, you can do it with the following JQuery (assuming you've gave your select an id of multiselect):

$(function () {
    $("#multiSelect").css("height", parseInt($("#multiSelect option").length) * 20);
});

Demo: http://jsfiddle.net/AZEFU/


I know the question is old, but how the topic is not closed I'll give my help.

The attribute "size" will resolve your problem.

Example:

<select name="courses" multiple="multiple" size="30">

select could contain optgroup which takes one line each:

<select id="list">
  <optgroup label="Group 1">
    <option value="1">1</option>
  </optgroup>
  <optgroup label="Group 2">
    <option value="2">2</option>
    <option value="3">3</option>
  </optgroup>
</select>
<script>
  const l = document.getElementById("list")
  l.setAttribute("size", l.childElementCount + l.length)
</script>

In this example total size is (1+1)+(1+2)=5.