簡體   English   中英

如何使用 Javascript 填充選擇框

[英]How to populate a select box with Javascript

我有一個帶有選擇框的簡單表單,我想用數據填充,但我不明白該怎么做。

這是我的表格:

<form name="form">    
 <select name="req_one" style="width:250px;"/> </select>    
</form>

這是我在我的 JS 中嘗試過的:

var name = 'test';
var i = 1;
document.form.req_one =new Option(name, i);

這應該導致等效的:

<option value="1"> Test </option>

我究竟做錯了什么?

您的 HTML 無效,您正在關閉選擇標簽

還要等到選擇在 DOM 中可用

這是一個例子

 window.addEventListener("load", function() { const name = 'test'; const value = 1; const sel = document.querySelector("[name=req_one]"); // or give it an ID and use document.getElementById("req_one") if (sel) { sel.options[sel.options.length] = new Option(name, value); } else { alert("Where did the sel go?"); } })
 <form name="myform"> <select name="req_one" style="width:250px;"></select> </form>

我建議使用 jquery 一個簡單的方法。

var name = 'test';
var i = 1;
$("select[name='req_one']").append('<option value="'+i+'">'+value+'</option>');

我希望你知道如何使用 jquery 。

你犯了一個小錯誤。 我整合了你的整個代碼:

<html>
<head>
<script type="text/javascript">
function l1(){
    var name = 'test';
    var i = 1;
    document.form.req_one.options[0] =new Option(name, i);//you forgot to include .options[0]
}
</script>
</head>
<body onload="l1()">
<form name="form">    
 <select name="req_one" style="width:250px;"/> </select>    
</form>
</body>
</html>

您忘記將新創建的Option添加到 select 元素的選項列表中:

document.form.req_one.options[0] = new Option(name, i);

JSFiddle 示例: http : //jsfiddle.net/zxT8U/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM