Categories
JavaScript Answers

How to Create a Form Dynamically with JavaScript?

Spread the love

Sometimes, we want to create a form dynamically with JavaScript.

In this article, we’ll look at how to create a form dynamically with JavaScript.

Create a Form Dynamically with JavaScript

To create a form dynamically with JavaScript, we can use the document.createElement method to create the element.

Then we can use the setAttribute method to set the element attributes.

Then we can use the appendChild method to append the elements into the parent element.

For instance, we can write:

const f = document.createElement("form");
f.setAttribute('method', "post");
f.setAttribute('action', "submit.php");

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

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

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

document.body.appendChild(f);

to create a form with an input and a submit button.

We write:

const f = document.createElement("form");
f.setAttribute('method', "post");
f.setAttribute('action', "submit.php");

to create a form element with the method and action attributes.

setAttribute takes the attribute name and value as arguments respectively.

Similar, we create the input by writing:

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

And the submit button we create by writing:

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

Next, we call appendChild on f to append both input elements as children of the form element by writing:

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

And finally, we append the form element as a child of the body element by writing:

document.body.appendChild(f);

Now we should see a form displayed on the screen after running the code that generated from the form.

Conclusion

To create a form dynamically with JavaScript, we can use the document.createElement method to create the element.

Then we can use the setAttribute method to set the element attributes.

Then we can use the appendChild method to append the elements into the parent element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *