如何在Javascript中动态添加文本框?

noo*_*oob 15 javascript dom textbox

默认情况下,我有5个文本框.当用户单击按钮时,应添加一个文本框.

我怎么能这样做?

CMS*_*CMS 22

如果替换innerHTML,将清除先前输入的值,为避免这种情况,您可以以编程方式附加输入元素:

var input = document.createElement('input'); 
input.type = "text"; 
//...    
container.appendChild(input); 
Run Code Online (Sandbox Code Playgroud)

检查示例.


Rob*_*uel 10

Javascript函数

function add() {

//Create an input type dynamically.
var element = document.createElement("input");

//Create Labels
var label = document.createElement("Label");
label.innerHTML = "New Label";     

//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "Test Name");
element.setAttribute("style", "width:200px");

label.setAttribute("style", "font-weight:normal");

// 'foobar' is the div id, where new fields are to be added
var foo = document.getElementById("fooBar");

//Append the element in page (in span).
foo.appendChild(label);
foo.appendChild(element);
}
Run Code Online (Sandbox Code Playgroud)

Html部分,

<button id="button" value="Add" onClick:"javascript:add();">
Run Code Online (Sandbox Code Playgroud)

它完成了!


Kyl*_*ndo 0

最好的方法是将一个事件附加到onclick按钮的 上,这会将 div 的可见性设置为inline。考虑到灵活性和稳健性,这是我能想到的最好的方法。

看看这里的示例代码。