Home >Web Front-end >JS Tutorial >How to Dynamically Populate a Select Element with Options in JavaScript?

How to Dynamically Populate a Select Element with Options in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 19:19:29254browse

How to Dynamically Populate a Select Element with Options in JavaScript?

JavaScript Function to Dynamically Populate Select Options

Problem:

The provided JavaScript function aims to create options from 12 to 100 in a options.

Customization and Reusability:

To enhance the usability of the function, we can allow customization of the minimum and maximum values. Here's an improved version that accepts additional parameters:

<code class="js">function populateSelect(selectElementId, min, max) {
  const select = document.getElementById(selectElementId);
  if (!min) { min = 0; }
  if (!max) { max = min + 100; }

  for (let i = min; i <= max; i++) {
    const option = document.createElement('option');
    option.value = i;
    option.textContent = i;
    select.appendChild(option);
  }
}</code>

This revised function enables you to specify the desired range of options for any