问题
Is it possible to dynamically populate a selectbox with options as well as optgroups, using the .options property of the element?
Simplified, this is what I'm doing now (imagine the loop is dynamic, have to do by script):
var demo = document.getElementById("d").children[0];
for (var i = 1; i <= 5; i++)
{
// this will in this case auto-select and default-select the third option
demo.options[demo.options.length] = new Option("Value: " + i, i, i == 3, i == 3);
}
<div id="d">
<select></select>
</div>
And I'd like to achieve a dom structure like this:
<div id="d">
<select>
<optgroup label='Something'>
<option ...
<option ...
</optgroup>
<optgroup label='Something else'>
<option ...
<option ...
<option ...
</optgroup>
</select>
</div>
I have full control over which and how many options are added to the selectbox, I just like to group them under certain criterias for clarity purposes (for this example just the first 2 and second 3, but not necessarily depending on iterator). But I cannot use any framework/library, it must be pure javascript. Also I'm aware of the createElement() method, however I'm using the options property and was just wondering if it could work with that.
If not possible I'd like to know what alternatives I have to dynamically creating optgroups, otherwise I'll just forgo using optgroups altogether.
回答1:
You will need to create the optgroup
element and append the options
you create to that element (and then append that optgroup
element to the select
element).
Here is a working example:
var demo = document.getElementById("d").children[0];
var optGroup = document.createElement('optgroup')
optGroup.setAttribute('label', 'some value')
for (var i = 1; i <= 5; i++)
{
// this will in this case auto-select and default-select the third option
optGroup.appendChild(new Option("Value: " + i, i, i == 3, i == 3))
}
demo.appendChild(optGroup)
var optGroup = document.createElement('optgroup')
optGroup.setAttribute('label', 'some other value')
for (var i = 6; i <= 10; i++)
{
// this will in this case auto-select and default-select the third option
optGroup.appendChild(new Option("Value: " + i, i, i == 3, i == 3))
}
demo.appendChild(optGroup)
<div id="d">
<select></select>
</div>
The Option() constructor is a non-standard constructor, however almost every browser has it. The <optgroup>
element on the other hand doesn't have such constructor, so in order to create it you must use the document.createElement
.
来源:https://stackoverflow.com/questions/41370840/how-to-dynamically-group-options-in-selectbox