我有一个带有选择框的简单表单,我想填充数据,但我不明白该怎么做。
这是我的表格:
<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>
关于javascript - 如何使用 Javascript 填充选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15082547/