jQuery-动态添加表单元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery-动态添加表单元素相关的知识,希望对你有一定的参考价值。

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2. "http://www.w3.org/TR/html4/loose.dtd">
  3. <html>
  4. <head>
  5. <title></title>
  6. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
  7.  
  8. <script type="text/javascript">
  9. $(document).ready(function() {
  10. $('#btnAdd').click(function() {
  11. var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
  12. var newNum = new Number(num + 1); // the numeric ID of the new input field being added
  13.  
  14. // create the new element via clone(), and manipulate it's ID using newNum value
  15. var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
  16.  
  17. // manipulate the name/id values of the input inside the new element
  18. newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
  19.  
  20. // insert the new element after the last "duplicatable" input field
  21. $('#input' + num).after(newElem);
  22.  
  23. // enable the "remove" button
  24. $('#btnDel').attr('disabled','');
  25.  
  26. // business rule: you can only add 5 names
  27. if (newNum == 5)
  28. $('#btnAdd').attr('disabled','disabled');
  29. });
  30.  
  31. $('#btnDel').click(function() {
  32. var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
  33. $('#input' + num).remove(); // remove the last element
  34.  
  35. // enable the "add" button
  36. $('#btnAdd').attr('disabled','');
  37.  
  38. // if only one element remains, disable the "remove" button
  39. if (num-1 == 1)
  40. $('#btnDel').attr('disabled','disabled');
  41. });
  42.  
  43. $('#btnDel').attr('disabled','disabled');
  44. });
  45. </script>
  46. </head>
  47.  
  48. <body>
  49.  
  50. <form id="myForm">
  51. <div id="input1" style="margin-bottom:4px;" class="clonedInput">
  52. Name: <input type="text" name="name1" id="name1" />
  53. </div>
  54.  
  55. <div>
  56. <input type="button" id="btnAdd" value="add another name" />
  57. <input type="button" id="btnDel" value="remove name" />
  58. </div>
  59. </form>
  60.  
  61. </body>
  62. </html>

以上是关于jQuery-动态添加表单元素的主要内容,如果未能解决你的问题,请参考以下文章

将 JQuery Datepicker 动态添加到表单元素

将 jQuery 验证规则添加到动态生成的表单元素时出错

jQuery-动态添加表单元素

如何动态添加带有引导表单元素的 div?

动态创建或删除表单元素

如何将 jquery ui 自动完成添加到动态创建的元素?