2016-12-28 10 views
1

要素の.optionsプロパティを使用して、オプションやoptgroupを動的に選択ボックスに入れることはできますか?selectboxのオプションを動的にグループ化する方法

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>

そして私は、DOMを達成したいと思います:簡体

が、これは(スクリプトで行う必要があり、ループは動的であると想像)私が今やっていることです

<div id="d"> 
    <select> 
    <optgroup label='Something'> 
     <option ... 
     <option ... 
    </optgroup> 
    <optgroup label='Something else'> 
     <option ... 
     <option ... 
     <option ... 
    </optgroup> 
    </select> 
</div> 

私はselectboxにどのオプションを追加するかを完全に制御できます。私はちょうどcertaの下にグループ化したいのです(この例では、最初の2番目と3番目のものだけですが、イテレータに必ずしも依存しません)。しかし、私はフレームワーク/ライブラリを使用することはできません、純粋なJavaScriptがする必要があります。また、私はcreateElement()メソッドを認識していますが、optionsプロパティを使用していて、それがうまくいくかどうか疑問に思っていました。

もし私がoptgroupsを動的に作成しなければならない代替案を知りたいのであれば、それ以外の場合はoptgroupsを一切使わないでください。

答えて

2

あなたはoptgroup要素を作成して追加する必要がありますoptionsあなたはその要素に作成し(その後、select要素にそのoptgroup要素を追加)。ここで

実施例である:

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>

Option() constructorは、しかし、ほとんどすべてのブラウザがそれを持って、非標準のコンストラクタです。一方、<optgroup>要素にはそのようなコンストラクタがないため、作成するにはdocument.createElementを使用する必要があります。

+0

私はcreateElement()を使用しないとできないと言っていますが、この方法でoptionsプロパティを使用することはできません。 –

+0

その通りです。私はこれに関するより多くの情報で答えを更新します。 – Dekel

+0

@JackMcKalling、更新を確認してください – Dekel

関連する問題