Add fields to a form using mustache.js to feed unique IDs.
A Pen by Joe Watkins on CodePen.
Add fields to a form using mustache.js to feed unique IDs.
A Pen by Joe Watkins on CodePen.
| <button type="button" class="btn btn-primary btn-xs add">Add</button> <button type="button" class="btn btn-default btn-xs remove">Remove</button> <span class="msg text-danger"></span> | |
| <hr> | |
| <form> | |
| <div class="container dynamic-rows"></div> | |
| </form> | |
| <script type="text/template" id="form_rows_tpl"> | |
| <div class="row"> | |
| <div class="col-lg-4"> | |
| <p> | |
| <label for="FirstName_{{count}}">{{count}}. First Name</label><br> | |
| <input type="text" name="FirstName" id="FirstName_{{count}}"> | |
| </p> | |
| </div> | |
| <div class="col-lg-4"> | |
| <p> | |
| <label for="LastName_{{count}}">Last Name</label><br> | |
| <input type="text" name="LastName" id="LastName_{{count}}"> | |
| </p> | |
| </div> | |
| <div class="col-lg-4"> | |
| <p> | |
| <label for="EmailAddress_{{count}}">Email Address</label><br> | |
| <input type="text" name="EmailAddress" id="EmailAddress_{{count}}"> | |
| </p> | |
| </div> | |
| </div> | |
| </script> |
| var template = $("#form_rows_tpl").html(), | |
| $target = $(".dynamic-rows"), | |
| $btnAdd = $("button.add"), | |
| $btnRemove = $("button.remove"), | |
| $msg = $('.msg'), | |
| max = 10, | |
| count = 1, | |
| inputRow = []; | |
| $btnAdd.click(function(e){ | |
| e.preventDefault(); | |
| addRows(); | |
| }); | |
| $btnRemove.click(function(e){ | |
| e.preventDefault(); | |
| removeRows(); | |
| }); | |
| function addRows(){ | |
| if(count <= max){ | |
| inputRow = { | |
| count : count | |
| } | |
| var html = Mustache.to_html(template, inputRow); | |
| $target.append(html); | |
| count++; | |
| }else{ | |
| $msg.text('too many fields!'); | |
| } | |
| } | |
| function removeRows(){ | |
| $target.find('.row').last().remove(); | |
| $msg.text(''); | |
| if(count <= 1){ | |
| count = 1; | |
| }else{ | |
| count--; | |
| } | |
| } | |
| addRows(); |
| body {margin:15px;} |