简体   繁体   English

使用JavaScript创建动态表单

[英]Creating dynamic form using javascript

I am trying to create forms dynamically using javascript, but I struggled with creating radio buttons in the form properly. 我正在尝试使用javascript动态创建表单,但是在正确创建表单中的单选按钮方面遇到了困难。 The problem is I can't display a label beside each radio button 问题是我无法在每个单选按钮旁边显示标签

here is the index.html file 这是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>

and the custom.js file 和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;

    }


}

Replace the last two lines of the for loop with 将for循环的最后两行替换为

form.appendChild(input[i]);
form.appendChild(option);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM