Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 843
pushpika liyanaarachchi Avatar asked Mar 04 '26 20:03

pushpika liyanaarachchi


1 Answers

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!

like image 168
Cyril Cherian Avatar answered Mar 06 '26 09:03

Cyril Cherian