javascript實現(xiàn)的動態(tài)添加表單元素input,button等(appendChild)
寫一個小系統(tǒng)時,需要動態(tài)添加表單元素,按自己的實現(xiàn)方法寫了這篇教程!
我想各位在很多網(wǎng)站上都看到過類似的效果!
1、先用document.createElement方法創(chuàng)建一個input元素!
var newInput = document.createElement("input");
2、設(shè)定相關(guān)屬性,如name,type等
newInput.type=mytype; newInput.name="input1";
3、用appendChild方法,將元素追加到某個標(biāo)簽內(nèi)容中!
TemO.appendChild(newInput);
Javascrip核心代碼:
<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");//創(chuàng)建一個BR標(biāo)簽是為能夠換行! TemO.appendChild(newline); } </script>
<html > <head> <title>動態(tài)添加表單元素</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"><br> </div> </form> <input name="" type="button" value="新建文本框" onClick="AddElement('text')" /> <input name="" type="button" value="新建復(fù)選框" 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="新建恢復(fù)按鈕" onClick="AddElement('reset')" /> </body> </html>
以上所述是小編給大家介紹的javascript實現(xiàn)的動態(tài)添加表單元素input,button等(appendChild),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
checkbox設(shè)置復(fù)選框的只讀效果不讓用戶勾選
有時候是只想告知用戶這個地方是可以進(jìn)行勾選操作的而不想讓用戶在此處勾選(比如在信息展示頁面),這時候就需要將復(fù)選框設(shè)置成只讀的效果,具體實現(xiàn)方法如下2013-08-08