M.Sameh
M.Sameh

Reputation: 85

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. The problem is I can't display a label beside each radio button

here is the index.html file

<!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

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;

    }


}

Upvotes: 0

Views: 90

Answers (1)

Waleed Iqbal
Waleed Iqbal

Reputation: 1322

Replace the last two lines of the for loop with

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

Upvotes: 1

Related Questions