Creating and submitting a form using javascript - Coding Sharp

Creating and submitting a form using javascript

In this article I will show you how to create a form dynamically using JavaScript and submit it.

JavaScript provides a way to create a DOM element easily using createElement method.

see the below code snippet for creating a form element

var form = document.createElement('form');

using same method you can create other element as well see the below code which creates input element

var field1 = document.createElement('input');

After creating form element you can set the action, method, target attributes of the form element as below.

form.method = 'POST';
form.action = 'urlToPost';
form.target = '_blank'

for filed element we need to set the name of the element and value of the element and need to add element to the form element as below

field1.name = 'username';
field1.value = field1val;
form.appendChild(field1);

after we add all the element to the form, we need to add form to the body of page and then submit the form as below

document.body.appednChild(form);
form.submit();

That’s it.

Now see the below complete function for Creating and submitting form using JavaScript.

function CreateandSubmitForm(urlToPost, field1val, field2val)
{
var form = document.createElement('form');
var field1 = document.createElement('input');
var field2 = document.createElement('input');

form.method = 'POST';
form.action = urlToPost;

field1.name = 'username';
field1.value = field1val;
form.appendChild(field1);

field2.name = 'password';
field2.value = field2val;
form.appendChild(field2);

document.body.appednChild(form);
form.submit();
}