creating form by using javascript for specific div tag

I need to create form by using JavaScript. Then I have created code as follows. I need to add this form to div id="form1"
by using getElementsById. But it does not working.

<html>
<head>
    <title>
    </title>
</head>
<body>
<div id="form1">
</div>
    <script>
            var f = document.createElement("form");
            f.setAttribute('method',"post");
            f.setAttribute('action',"submit.php");

            var i = document.createElement("input");
            i.setAttribute('type',"text");
            i.setAttribute('name',"username");

            var s = document.createElement("input"); 
            s.setAttribute('type',"submit");
            s.setAttribute('value',"Submit");

            f.appendChild(i);
            f.appendChild(s);

            document.getElementsById("form1")[0].appendChild(f);
</script>
</body>
</html>

Upvotes: 3

Views: 1482

Answers (2)

Cyril Cherian
Cyril Cherian

Reputation: 32327

It has to be like this:

document.getElementById("form1").appendChild(f);

This is wrong:

document.getElementsById("form1")[0].appendChild(f);

working code here

EDIT

Here is how you can append a table

Hope this helps!

Upvotes: 1

Luke
Luke

Reputation: 2168

Change document.getElementsById to document.getElementById and take out the [0].

<body>
<div id="form1">
</div>
<script>
        var f = document.createElement("form");
        f.setAttribute('method',"post");
        f.setAttribute('action',"submit.php");

        var i = document.createElement("input"); //input element, text
        i.setAttribute('type',"text");
        i.setAttribute('name',"username");

        var s = document.createElement("input"); //input element, Submit button
        s.setAttribute('type',"submit");
        s.setAttribute('value',"Submit");

        f.appendChild(i);
        f.appendChild(s);

        //and some more input elements here
        //and dont forget to add a submit button

        document.getElementById("form1").appendChild(f);
</script>
</body>

Have a look here: https://jsfiddle.net/L65fpfjj/

:)

Upvotes: 0

Related Questions