最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - How to add inputs to a form only with javascript - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Dec 11, 2017 at 14:51 kyun 10.3k9 gold badges35 silver badges79 bronze badges asked Dec 11, 2017 at 14:49 DanielDaniel 711 gold badge1 silver badge9 bronze badges 2
  • 2 please post what you have written so far – messerbill Commented Dec 11, 2017 at 14:49
  • I'm waiting for a better solution before I start writing – Daniel Commented Dec 11, 2017 at 14:52
Add a ment  | 

2 Answers 2

Reset to default 2

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);

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>

发布评论

评论列表(0)

  1. 暂无评论