div id="header">
www.encodedna.com

How to expand SELECT element options automatically on page load using JavaScript

← PrevNext →

Let us assume, I have a SELECT dropdown list on my web page with few options (or values) in it. I want to expand the SELECT options (or list) automatically on page load. Here's a simple method to do this.
<body>
  <select id='sel'>
    <option>-- Choose a Name --</option>
    <option value='Mourning Dove'>Mourning Dove</option>
    <option value='Rock Pigeon'>Rock Pigeon</option>
    <option value='Eurasian Collared-Dove'>Eurasian Collared-Dove</option>
    <option value='Monk Parakeet'>Monk Parakeet </option>
    <option value='Inca Dove'>Inca Dove</option>
  </select>
</body>

<script>
    window.onload = function () {
      const element = document.getElementById('sel');   
        element.size = 4;  // set the "number" of visible options.
    };
</script>
Try it

In the above script, see the size property (in bold), which I have assigned to the element (the SELECT element) object. The "size" property or attribute speficies the number of SELECT options that will be visible. The value must be an integer value.

I am assigning the "size" attribute dynamically in JavaScript. However, you can assign the property when declaring the SELECT element. For example,

<select id='sel' size='3'>
    <option>-- Choose a Name --</option>
    <option value='Mourning Dove'>Mourning Dove</option>
    <option value='Rock Pigeon'>Rock Pigeon</option>
    <option value='Eurasian Collared-Dove'>Eurasian Collared-Dove</option>
    <option value='Monk Parakeet'>Monk Parakeet </option>
    <option value='Inca Dove'>Inca Dove</option>
  </select>

← PreviousNext →