我正在尝试使用 javascript 动态创建表单,但我很难在表单中正确创建单选按钮。问题是我无法在每个单选按钮旁边显示标签
这是index.html文件
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
</head>
<body>
<form id="myform">
</form>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
和 custom.js 文件
document.body.onload = newElement;
function newElement() {
var form = document.getElementById("myform");
var questions = {
name : "q1",
qType : "radio",
qLabel : "Is your system is automated online advising?",
options : ["Yes", "No"]
}
var label = document.createElement("label");
var lblContent = document.createTextNode(questions["qLabel"]);
label.appendChild(lblContent);
form.appendChild(label);
switch(questions["qType"]) {
case "radio":
var input = [];
var option;
var optionContent;
for(var i = 0; i < questions["options"].length; i++) {
input[i] = document.createElement("input");
input[i].setAttribute("type", questions["qType"]);
input[i].setAttribute("name", questions["name"]);
option = document.createElement("label");
optionContent = document.createTextNode(questions["options"][i]);
option.appendChild(optionContent);
input[i].appendChild(option);
form.appendChild(input[i]);
}
break;
}
}
最佳答案
将 for 循环的最后两行替换为
form.appendChild(input[i]);
form.appendChild(option);
关于javascript - 使用 javascript 创建动态表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48387320/