Home > Article > Web Front-end > How to Dynamically Create Options in a Select Element Using JavaScript?
Q: I want to create options from 12 to 100 in a select element with the ID "mainSelect" dynamically. How can I achieve this without manually creating each option tag?
A: Here's a solution using a simple for loop:
var min = 12, max = 100, select = document.getElementById('selectElementId'); for (var i = min; i<=max; i++){ var opt = document.createElement('option'); opt.value = i; opt.innerHTML = i; select.appendChild(opt); }
In this code:
This approach is efficient and allows you to easily create a range of options dynamically for any given select element.
The above is the detailed content of How to Dynamically Create Options in a Select Element Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!