发布于:,更新于:

js代码创建表单控件

简洁javascript实现动态添加form,div,input等元素至html中

1.IDE:

  • JetBrains webStorm

2.目的:点击按钮,自动添加新form

(ps:动态添加div,input等其他元素应该同理,这里只拿form举例)

3.涉及的javascript函数:

  1. objNode.getElementId();
  2. objNode.parentNode;
  3. objNode.cloneNode(true);
  4. objNode.appendChild();

4.操作前后效果图对比(操作:点击“添加新表单”)

4.1 操作前:

添加表单前

4.2操作后:

添加表单后

4.3对比结果:

点击后立刻动态添加了新的form,form个数由1变成2。

5.实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<div id="f_div" class="panel-body" >	  

<!--待复制表单---->
<form id="form_edu" role="form" class="form-horizontal edit_form" >
<!--表单中代码略---->
</form>

<!--动作按钮,点击触发addform---->
<button type="button" class="btn-primary" onclick="addform()">添加新表单</button>

<!--动作代码---->
<script>
function addform() {

<!--获得id为“form_edu"的form的父节点对象,即id为"f_div"的div,命名为f_Div---->
f_Div = document.getElementById("form_edu").parentNode;

<!--克隆”form_edu",记为"newform1"(克隆函数会克隆目标的一切属性)---->
var newform1 = document.getElementById("form_edu").cloneNode(true);

<!--更改"newform1"的id,使其id不和”form_edu"重复--->
newform1.id = "form_edu1";

<!--更改"newform1"的边框颜色,便于演示观察--->
newform1.style.borderColor="#0d2798";

<!--把"newform1"追加进父节点f_div--->
f_Div.appendChild(newform1);
}
</script>
</div>

6.补充:

代码中也可以通过指定父节点id直接获取form_edu的父节点对象:
f_Div = document.getElementById(“f_div”);