jquery 动态添加表单元素
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jquery 动态添加表单元素相关的知识,希望对你有一定的参考价值。
如图所示当点击添加一行是就动态添加多一行表单元素。请问用jquery怎么实现,或者有网站做参考。谢谢网友的回答。。
参考技术A 可以在表单中使用table 然后对table进行动态的添加。//监听添加表格行数的阿按扭
$(document).ready(function()
$("#but").click(function()
var $table=$("#tab tr");
var len=$table.length;
$("#tab").append("<tr id="+(len+1)+"><td align=\'center\'><img width=\'140\' src=\'images/1.jpg\'></td><td align=\'center\'><a href=\'javascript:void(0)\' onclick=\'deltr("+(len+1)+")\'>删除</a></td></tr& gt;");
)
)
//删除指定的表格的行
function deltr(index)
$table=$("#tab tr");
$("tr[id=\'"+index+"\']").remove();
以下写在body中即可
//添加按钮
<input id="but" type="button" value="添加" />
//空的表格
<table class="print_product_img" id="tab" border="1" width="60%" align="center">
</table>
jQuery-动态添加表单元素
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#btnAdd').click(function() { var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have var newNum = new Number(num + 1); // the numeric ID of the new input field being added // create the new element via clone(), and manipulate it's ID using newNum value var newElem = $('#input' + num).clone().attr('id', 'input' + newNum); // manipulate the name/id values of the input inside the new element newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum); // insert the new element after the last "duplicatable" input field $('#input' + num).after(newElem); // enable the "remove" button $('#btnDel').attr('disabled',''); // business rule: you can only add 5 names if (newNum == 5) $('#btnAdd').attr('disabled','disabled'); }); $('#btnDel').click(function() { var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have $('#input' + num).remove(); // remove the last element // enable the "add" button $('#btnAdd').attr('disabled',''); // if only one element remains, disable the "remove" button if (num-1 == 1) $('#btnDel').attr('disabled','disabled'); }); $('#btnDel').attr('disabled','disabled'); }); </script> </head> <body> <form id="myForm"> <div id="input1" style="margin-bottom:4px;" class="clonedInput"> Name: <input type="text" name="name1" id="name1" /> </div> <div> <input type="button" id="btnAdd" value="add another name" /> <input type="button" id="btnDel" value="remove name" /> </div> </form> </body> </html>
以上是关于jquery 动态添加表单元素的主要内容,如果未能解决你的问题,请参考以下文章