Home >Web Front-end >JS Tutorial >How to Dynamically Populate a Select Element with Options in JavaScript?
Problem:
The provided JavaScript function aims to create options from 12 to 100 in a
Solution:
To resolve this issue, we can utilize a simple for loop:
<code class="js">const min = 12; const max = 100; const select = document.getElementById('mainSelect'); for (let i = min; i <= max; i++) { const option = document.createElement('option'); option.value = i; option.textContent = i; select.appendChild(option); }</code>
This approach provides a more efficient and automated way to populate the
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
The above is the detailed content of How to Dynamically Populate a Select Element with Options in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!