jQuery - Dynamically Adding Form Elements


/ Published in: jQuery
Save to your folder(s)



Copy this code and paste it in your HTML
  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>

URL: http://charlie.griefer.com/blog/index.cfm/2009/9/17/jQuery--Dynamically-Adding-Form-Elements

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.