在新行中动态添加更多文本字段(html)

时间:2012-09-01 04:10:15

标签: javascript html dom

我使用了来自http://viralpatel.net/blogs/dynamic-add-textbox-input-button-radio-element-html-javascript/ html-javascript / .my代码的代码:

<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function add() {

    for (i=1; i<=5; i++)
      {
        //Create an input type dynamically.
        var element = document.createElement("input");
     
        //Assign different attributes to the element.
        element.setAttribute("type", i);
        element.setAttribute("name", i);
        element.setAttribute("value", i);
     
     
        var foo = document.getElementById("fooBar");
     
        //Append the element in page (in span).
        foo.appendChild(element);
      }

 
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<INPUT type="button" value="Add" onclick="add()"/>
     
<span id="fooBar">&nbsp;</span>
     
</FORM>
</BODY>
</HTML>

该代码有效。但是,我希望每个新文本字段都添加一个新行,而不是水平添加它。我尝试在循环函数中使用</script><br/><script><html><br/></html>document.write("\n")document.write("\r\n"),但它并不像我想要的那样工作。我该怎么办?

4 个答案:

答案 0 :(得分:4)

为什么不这样做?

var br = document.createElement("br");
foo.appendChild(br);

答案 1 :(得分:1)

您可以更改输入的显示样式。

function add() {

    for (i=1; i<=5; i++)
      {
        //Create an input type dynamically.
        var element = document.createElement("input");

        //Assign different attributes to the element.
        element.setAttribute("type", i);
        element.setAttribute("name", i);
        element.setAttribute("value", i);
        element.style.display = "block";

        var foo = document.getElementById("fooBar");

        //Append the element in page (in span).
        foo.appendChild(element);
      }
}
祝你好运! 我建议你开始使用jQuery来完成你的javascript任务。

答案 2 :(得分:0)

您可以尝试在输入元素之后添加新的br元素。

  for (i=1; i<=5; i++)
  {
    //Create an input type dynamically.
    var element = document.createElement("input");

    //Assign different attributes to the element.
    element.setAttribute("type", i);
    element.setAttribute("name", i);
    element.setAttribute("value", i);

    var brElement = document.createElement("br");

    var foo = document.getElementById("fooBar");

    //Append the element in page (in span).
    foo.appendChild(element);
    foo.appendChild(brElement );
  }

答案 3 :(得分:0)

您只需将其添加到您的css

即可
input{display:block;}