"Dynamic Form Fields - Add & Remove"
Bootstrap 2.3.2 Snippet by Lewiscowles1986

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="container"> <div class="row"> <input type="hidden" name="count" value="1" /> <div class="control-group" id="fields"> <label class="control-label" for="field1">Nice Multiple Form Fields</label> <div class="controls" id="profs"> <form class="input-append"> <div class="row-fluid"> <div id="container"> </div> </div> <div class="row-fluid"> <input autocomplete="off" class="input" id="field1" name="prof1" type="text" placeholder="Type something" data-items="8"/> <button id="b1" class="btn add" type="button">+</button> </div> </form> <br> <small>Press + to add another form field :)</small> </div> </div> </div> </div>
* { .border-radius(0) !important; } #field { margin-bottom:20px; }
$(document).ready(function(){ window.countElementsIn = function(containerSel, patternSel) { var parentE = jQuery(containerSel); var parentCnt = parentE.length; if(parentCnt > 0) { return parentE.find(patternSel); } return 0; } window.genInput = function(baseName,type,val,extraClass) { return '<input class="input form-control '+extraClass+'" name="'+baseName+'[]" type="'+type+'" value="'+val+'">'; } window.genBtn = function(label,extraClass) { return '<button class="btn '+extraClass+'" >'+label+'</button></div>'; } window.genNewRow = function(type,val) { switch(type) { default: return '<div class="row-fluid record"><div class="span12">'+genInput('field','text',val)+' '+genBtn('-', 'btn-danger remove-parent')+'</div></div>'; } console.log('Check your code Im broken...') return ''; // should never happen } jQuery(".add").on('click', function(e){ e.preventDefault(); // prevents button weird behaviour var me = jQuery(this); var addTo = me.data('append-to') != undefined ? me.data('append-to') : "#container"; var newType = me.data('append-type') != undefined ? me.data('append-type') : 'text'; // text is just default var newRec = genNewRow( newType, me.prev().val() ); jQuery(addTo).append( newRec ); me.prev().val(''); // wipe our value jQuery('.remove-parent').click(function(){ e.preventDefault(); // prevents button weird behaviour jQuery(this).parent().remove(); }); }); });

Related: See More


Questions / Comments: