Daniel
Daniel

Reputation: 71

How to add inputs to a form only with javascript

Only with Javascript

I want to create a form and, depends on your choice, you will see some fields or others.

I thought I can do that with a getElementById() and using innerHTML to override all of the forms, however I'm searching for another way that doesn't override all the form and just add a new input

Upvotes: 1

Views: 11254

Answers (2)

Jason Delaney
Jason Delaney

Reputation: 458

Here is a simple example using the createElement, using just javascript you can build nice dynamic forms

<!DOCTYPE html>
<html>
<body>

<p>Click the button.</p>

<button onclick="myFunction()">Add Input Field</button>
<button onclick="myFunctionTwo()">Add Radio button</button>


<script>
function myFunction() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value", "You Just added a text field ");
    document.body.appendChild(x);
}
function myFunctionTwo() {
    var y = document.createElement("INPUT");
    y.setAttribute("type", "radio");
    document.body.appendChild(y);
}
</script>

</body>
</html>

Upvotes: 0

Sudhi
Sudhi

Reputation: 91

Using Javascript, all you need is document.createElement and setAttribute.

var input = document.createElement("input");
input.setAttribute('type', 'text');

Then you can use appendChild to append the created element to the desired parent element.

var parent = document.getElementById("parentDiv");
parent.appendChild(input);

Upvotes: 2

Related Questions