web-dev-qa-db-ja.com

ドロップダウンリストを作成して選択した値を取得するJavaScript

ドロップダウンリストをWebページに追加する必要があります。通常、HTMLコードは次のようになります。

<select id="au_1_sel" name="au_1_sel" class="searchw8">
    <option value="AU" selected="">method1</option>
    <option value="FI">method2</option>
</select>

JavaScriptを使用して上記のような要素を作成するにはどうすればよいですか。このドロップダウンリストを作成した後。ボタンの後に追加する必要があります。

var button = document.getElementById("button1");

そして、私はすでにボタン要素を取得しています。また、ボタンがクリックされたときに、ユーザーがドロップダウンリストで選択したオプションを知りたいです。 JavaScriptを使用してどうすればよいですか。

私はこれを試します

var select = document.createElement("select");
select.id = "wayToCalculate";
//select.name="au_1_sel";
//select.class=class="searchw8";

var option1 = document.createElement("option");
option1.value="1";
option1.selected="";
option1.innerHTML= "1";

var option2 = document.createElement("option");
option2.value="2";
option2.innerHTML= "2";

var option3 = document.createElement("option");
option3.value="3";
option3.innerHTML= "3";

select.addChild(option1);
select.addChild(option2);
select.addChild(option3);

$(select).insertAfter(button);

しかし、これに関しては。 select.addChild(option1);

chromeブラウザでエラーが発生します。

Uncaught TypeError: undefined is not a function

ここではaddChildが機能しないようです。

8
atekul

[〜#〜] html [〜#〜]

<div id="container">   
    <button id="button1">button1</button>
</div> 

JavaScript

var div = document.querySelector("#container"),
    frag = document.createDocumentFragment(),
    select = document.createElement("select");

select.options.add( new Option("Method1","AU", true, true) );
select.options.add( new Option("Method2","FI") );


frag.appendChild(select);
div.appendChild(frag);
10
Chase
var select = document.createElement("select");
select.id = "au_1_sel";
select.name="au_1_sel";
select.class=class="searchw8";

var option1 = document.createElement("option");
option.value="AU";
option.selected="";
option.innerHTML= "method1";

var option2 = document.createElement("option");
option.value="FI";
option.innerHTML= "method2";

select.addChild(option1);
select.addChild(option2);
document.addChild(select);

var button = document.getElementById("button1");
button.onClick=function(){alert(select.options[select.selectedIndex].value);}
4
nicael