
这样:
<body>
<form id='form'> --定义form
</form>
<script>
var input = document.createElement('input') //创建input节点
input.setAttribute('type', 'text') //定义类型是文本输入
document.getElementById('form').appendChild(input ) //添加到form中显示
</script>
</body>
扩展资料:注意事项
一、form属性可以使input标签不再form表单内时也属于form表单中的一部分
<form action="xxx" id="forms">
<input type="submit" value="提交">
</form>
<input type="text" form="forms" name="names">
<!-- IE中不支持这个属性 -->
二、JavaScript提交表单时,可以在input标签内添加required属性,在内容为空的时候阻止表单提交。
使用required属性时添加oninvalid属性可以自定义提示文字
<form action="xxx" method="post">
<input type="text" name="fname" required oninvalid="setCustomValidity('不能为空')">
<input type="submit" value="提交">
</form>
<!-- IE9及更早版本不支持 -->
1、先用document.createElement方法创建一个input元素! var newInput = document.createElement("input")
2、设定相关属性,如name,type等
newInput.type=mytype
newInput.name="input1"
3、用appendChild方法,将元素追加到某个标签内容中!
TemO.appendChild(newInput)
<html >
<head>
<title>动态添加表单元素</title>
</head>
<script language="javascript">
function AddElement(mytype){
var mytype,TemO=document.getElementById("add")
var newInput = document.createElement("input")
newInput.type=mytype
newInput.name="input1"
TemO.appendChild(newInput)
var newline= document.createElement("br")
TemO.appendChild(newline)
}
</script>
<body>
<form action="" method="get" name="frm">
<div id="add">
<input type="text" name="textfield">
</div>
</form>
<input name="" type="button" value="新建文本框" onClick="AddElement('text')" />
<input name="" type="button" value="新建复选框" onClick="AddElement('checkbox')" />
<input name="" type="button" value="新建单选框" onClick="AddElement('radio')" />
<input name="" type="button" value="新建文件域" onClick="AddElement('file')" />
<input name="" type="button" value="新建密码框" onClick="AddElement('password')" />
<input name="" type="button" value="新建提交按钮" onClick="AddElement('submit')" />
<input name="" type="button" value="新建恢复按钮" onClick="AddElement('reset')" />
</body>
</html>
运行效果:
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)