Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create a HTML form with Javascript

how can I go about creating a form with javascript?

I have NO idea on how to proceed, I have been googling my face off but there is nothing definitive that can show me how to dynamically create forms with it.

Thanx in advance!

like image 402
Odyss3us Avatar asked Jul 21 '10 07:07

Odyss3us


People also ask

How do I create a dynamic form in HTML?

The task is to create an HTML form dynamically with the help of JavaScript. There are two approaches that are discussed below. Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements.

Can HTML elements be create dynamically using JavaScript?

createElement() method you can create a specified HTML element dynamically in JavaScript. Once created, you can insert (or add) the element to your web page, or add it to a pre-defined element or a dynamically created element. In fact, you can create an entire form dynamically using this method.

Can you make a form with JavaScript?

JavaScript uses the HTMLFormElement object to represent a form. The HTMLFormElement has the following properties that correspond to the HTML attributes: action – is the URL that processes the form data. It is equivalent to the action attribute of the <form> element.


1 Answers

You could try something like this:

The HTML part:

<html>
 <head></head>
 <body>

 <body>
</html>

The javascript:

<script>
//create a form
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

//create input element
var i = document.createElement("input");
i.type = "text";
i.name = "user_name";
i.id = "user_name1";

//create a checkbox
var c = document.createElement("input");
c.type = "checkbox";
c.id = "checkbox1";
c.name = "check1";

//create a button
var s = document.createElement("input");
s.type = "submit";
s.value = "Submit";

// add all elements to the form
f.appendChild(i);
f.appendChild(c);
f.appendChild(s);

// add the form inside the body
$("body").append(f);   //using jQuery or
document.getElementsByTagName('body')[0].appendChild(f); //pure javascript

</script>

This way you can create as many elements as you want dynamically.

like image 193
user1451533 Avatar answered Oct 18 '22 22:10

user1451533