2010-07-21 60 views
13

我该如何去创建一个JavaScript表单?用Javascript动态创建一个HTML表单

我对如何进行没有任何想法,我一直在使用Google搜索,但没有任何明确指示可以告诉我如何动态创建表单。

Thanx提前!

+0

基本上,就像您使用'createElement'或jQuery创建其他JavaScript元素一样。你可以使用jQuery吗? – 2010-07-21 07:42:22

+0

是的,我可以使用jQuery,但不是太熟悉。 – Odyss3us 2010-07-21 07:55:58

回答

5

我认为发布一个完整的解决方案将是太多,但检查出的jQuery这一点。 我给你一个提示,jQuery的.append()能为你是非常有用的:)

0

我的建议是获得underscore.js库并使用它的template函数来创建表单。 (如果下划线对您来说太大,模板功能也可以自行设置)。

3

是的,你可以创建HTML包括运行的JavaScript形式的任何金额,

也许:`

<html> 
    <body> 
    <h1>My Form</h1> 
    <div id="formcontent"> 
    </div> 
    </body> 
</html> 

我们的JavaScript可能看起来像:

var e1 = document.CreateElement("input"); 
el.type = "text"; 
el.name = "myformvar"; 

var cont = document.GetElementById("formcontent") 
cont.appendChild(e1); 
0

试试这个.. 。

myWin = open("", "displayWindow", "width=800,height=500,status=yes,toolbar=yes,menubar=yes"); 

       myWin.document.open(); 
       myWin.document.write("<html><head><title>V E N U S </title>"); 
       myWin.document.write("<style type='text/css'>.hdr{.......}</style>"); 
        myWin.document.write("</head><body onload='window.print()'>"); 
          myWin.document.write("<div class='hdr'>"); 

           myWin.document.write("what ever you want"); 
           . 
           . 


         myWin.document.write("</div>");    
        myWin.document.write("</body></html>"); 
       myWin.document.close(); 

这将创建一个与它里面DIV形式...

25

你可以尝试这样的事:

的HTML部分:

<html> 
<head></head> 
<body> 

<body> 
</html> 

的JavaScript:

<script> 
//create a form 
var f = document.createElement("form"); 
f.setAttribute('method',"post"); 
f.setAttribute('action',"submit.php"); 

//create input element 
var i = document.createElement("input"); 
i.type = "text"; 
i.name = "user_name"; 
i.id = "user_name1"; 

//create a checkbox 
var c = document.createElement("input"); 
c.type = "checkbox"; 
c.id = "checkbox1"; 
c.name = "check1"; 

//create a button 
var s = document.createElement("input"); 
s.type = "submit"; 
s.value = "Submit"; 

// add all elements to the form 
f.appendChild(i); 
f.appendChild(c); 
f.appendChild(s); 

// add the form inside the body 
$("body").append(f); //using jQuery or 
document.getElementsByTagName('body')[0].appendChild(f); //pure javascript 

</script> 

这你可以动态地创建尽可能多的元素。

+0

该解决方案效果很好。谢谢! – 2014-03-01 22:34:40

+0

如果在脚本执行的时候没有加载DOM,你可能会得到一个错误 - 在我的例子中,我得到了“无法读取未定义的属性'appendChild'”。所以最好把javascript代码放在window-onload块中。 例如, Dilruk 2017-09-24 20:45:07

3

我的想法是,您可以使用github上的dform jquery插件直接通过给出输入为json数据来创建表单。