2014-05-18 20 views
6

Tôi cần phải thêm danh sách thả xuống vào trang web. nói chung mã HTML là như thế này;JavaScript để tạo danh sách thả xuống và nhận giá trị đã chọn

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

Tôi làm cách nào để sử dụng JavaScript để tạo thành phần như trên. sau khi tôi tạo danh sách thả xuống này. Tôi cần phải thêm nó sau một nút.

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

và tôi đã nhận được phần tử nút. Ngoài ra, khi nút được nhấp, tôi muốn biết tùy chọn mà mọi người đã chọn trong danh sách thả xuống. Làm thế nào tôi có thể làm điều đó bằng cách sử dụng JavaScript.

tôi cố gắng này

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); 

nhưng khi nói đến việc này. select.addChild (option1);

trình duyệt Chrome cho tôi lỗi.

Uncaught TypeError: undefined is not a function 

Dường như addChild không hoạt động ở đây.

+0

Ông có thể cho chúng ta thấy những gì bạn đã cố gắng cho đến nay? –

+0

Bạn đã có nút trong html của mình? – nicael

+0

xin lỗi, tôi đã tìm kiếm, nhưng chưa tìm thấy giải pháp, vì vậy tôi đăng ở đây.và có, nút tôi đã có – atekul

Trả lời

7

Example

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); 
+0

xin lỗi, tôi thấy câu trả lời của bạn là chính xác .. Tôi đã không kiểm tra mã ngày hôm qua. – atekul

+0

cách cung cấp thuộc tính id và tên trong mã ở trên –

4
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);} 
+0

xin lỗi, mã là vấn đề. – atekul

Các vấn đề liên quan