Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joe-watkins/9057596 to your computer and use it in GitHub Desktop.
Save joe-watkins/9057596 to your computer and use it in GitHub Desktop.
A Pen by Joe Watkins.
<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;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment