如何使用javascript动态创建表单?

时间:2014-01-01 07:42:17

标签: javascript jquery html forms

下面的代码动态地将文本内容添加到列表中,

window.onload = function()
{
    //alert("Window is loaded");

    var numberList = document.getElementById("numberList");


    //for every number between 100 and 200      
    for(var i = 0; i > 100 && i < 200; i++)
    {
        if ( i % 17 == 0 && i % 2 == 0) //if number evenly divisible by 17 and 2
        {
                    //create new li element
            var newNumberListItem = document.createElement("li");

                    //create new text node
            var numberListValue = document.createTextNode(i);

                    //add text node to li element
            newNumberListItem.appendChild(numberListValue);

                    //add new list element built in previous steps to unordered list
                    //called numberList
            numberList.appendChild(newNumberListItem);

        }
    }
}

现在,我想添加一个包含一个文本字段和一个提交按钮的表单,而不是像“i”这样添加文本内容。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

举个例子,您可以根据自己的要求进行更改

内部脚本标记

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

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

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

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

document.getElementsByTagName('body')[0].appendChild(f);

答案 1 :(得分:1)

在javascript中尝试这样的事情......

      /*Form creation*/
      var form = document.createElement("form");
      var input = document.createElement("input");

      form.action = "FileNameHere";
      form.method = "post";

      input.name = "name";
      input.value = "testname";
      form.appendChild(input);

      form.submit();