0

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;

    }


}
2
  • append the radio buttons to labels ..? Commented Jan 22, 2018 at 17:41
  • You can do this by replacing input[i].appendChild(option); with form.appendChild(option);. Commented Jan 22, 2018 at 17:46

1 Answer 1

1

Replace the last two lines of the for loop with

form.appendChild(input[i]);
form.appendChild(option);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.