簡體   English   中英

使用JavaScript創建動態表單

[英]Creating dynamic form using javascript

我正在嘗試使用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);

暫無
暫無

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

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