Create HTML Form with JavaScript

This tutorial is all about creating form using JavaScript.

In this tutorial, we are going to see how to create simple html form using JavaScript step by step.

So if you want to create a form dynamically with javascript, you must read this tutorial.

Live Demo

First we write HTML markup.

HTML

<html>   
<body>
<div id="formcontent">
</div>
</body>
</html>

JavaScript

Here we write script to create form and append it above div.

<script> 
var content = document.getElementById("formcontent");
var url = 'http://www.phpcluster.com';
var form = document.createElement("form");
form.setAttribute('method', 'post');
form.setAttribute('action', url);
form.setAttribute('target', 'pclu');

// Create an input
var heading = document.createElement('h2'); // Heading of Form heading.innerHTML = "Form ";
form.appendChild(heading);

var linebreak = document.createElement('br');
form.appendChild(linebreak);

var namelabel = document.createElement('label'); // Create Label for Name Field namelabel.innerHTML = "Name : "; // Set Field Labels form.appendChild(namelabel);
var inputelement = document.createElement('input'); // Create Input Field for Name inputelement.setAttribute("type", "text"); inputelement.setAttribute("name", "name");
form.appendChild(inputelement);

var linebreak = document.createElement('br');
form.appendChild(linebreak);

var emaillabel = document.createElement('label'); // Create Label for E-mail Field emaillabel.innerHTML = "Email : ";
form.appendChild(emaillabel); var inputelement = document.createElement('input'); // Create Input Field for Name inputelement.setAttribute("type", "email"); inputelement.setAttribute("name", "email");
form.appendChild(inputelement);

var linebreak = document.createElement('br');
form.appendChild(linebreak);

var inputbutton = document.createElement('input'); // Create Input Field for Name
inputbutton.setAttribute("type", "button"); inputbutton.setAttribute("name", "submit"); inputbutton.setAttribute("value", "Submit");
form.appendChild(inputbutton);
content.appendChild(form); </script>

Hope you have created your own form using JavaScript. If you have any query feel free to comment.

Leave a Comment