0

I want to make a webpage that can dynamically add checkbox.

The follows is my code. It can add label, however, it can't add checkbox. I don't know the reason?

<html>
<head>
    <script text="text/javascript">
        function dynamicAdd(){
            var name = document.getElementById("addName");
            var checkbox= document.createElement(name.value);
            checkbox.type="checkbox";
            checkbox.name=name.value;
            checkbox.value=name.value;
            checkbox.id=name.value;

                var label = document.createElement("label");
                label.htmlFor="id";
                label.appendChild(document.createTextNode("text for label after checkbox"));

                var container = document.getElementById("checklist");
                container.appendChild(checkbox);
                container.appendChild(label);


            }
    </script>
</head>
<body>
    <form  id="checklist">
        <input type="checkbox"  value="windows">Windows Clean</input><br>
        <input type="checkbox"  value="floor">Floor Clean</input><br>

    </form>
        <input type="text" id="addName" size="25" maxlength="50" value="elevator"><br>
        <Button type="button" onclick="dynamicAdd()" name="add">AddOption</button>
</body>
</html>
0

1 Answer 1

1
document.createElement(name.value);

Is false, according to this (@Quentin).

Text extract from the link

...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";

var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));

container.appendChild(checkbox);
container.appendChild(label);
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.