"dynamic form builder"
Bootstrap 4.0.0 Snippet by xrozix

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/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="expandable form-group" data-count="1"> <div class="row"> <label class="col-md-1 offset-md-2" for="name[]">Name(s):</label> <input name="name[]" type="text" id="name[]" value="name"> <button class="btn add-more" id="add-more" type="button">+</button> </div> </div> <br> <div class="expandable form-group" data-count="1"> <div class="row"> <label class="col-md-1 offset-md-2" for="name[]">Surname:</label> <input name="surname[]" type="text" id="surname[]" value="surname"> <button class="btn add-more" id="add-more" type="button">+</button> </div> </div> </div>
$(document).ready(function() { $(".expandable").on("click", ".add-more", function(e) { e.preventDefault(); var rmButton = '<button class="btn btn-danger remove-me" type="button">-</button>'; var grandParent = $(this).parent().parent(); var countVal = grandParent.data("count"); var count = parseInt(countVal); if (count == 1) { $(this).before(rmButton); } var toBeCopied = $(this).parent().clone(); if (count == 1) { var curClass = toBeCopied.find("input").attr('class'); toBeCopied.find("input:first").attr('class', curClass + " offset-md-3"); toBeCopied.find("label").remove(); } var add_button = $(this).detach(); grandParent.append(toBeCopied); count++; grandParent.data("count", count); }); $(".expandable").on("click", ".remove-me", function(e) { e.preventDefault(); var grandParent = $(this).parent().parent(); var countVal = grandParent.data("count"); count = parseInt(countVal); count--; grandParent.data("count", count); var nextButton = $(this).next("button"); var prevButton = $(this).parent().prev().find("button"); //When we click remove on the last entry: if (/add-more/.test(nextButton.attr("class")) && /remove-me/.test(prevButton.attr("class"))) { var add_button = nextButton.detach(); $(this).parent().prev().find(".remove-me").after(add_button); } //When we click on the first entry: if ($(this).parent().children().is("label")) { secondEntry=$(this).parent().next().find("input"); secondEntry.removeClass("offset-md-3"); secondEntry.before($(this).parent().find("label")); } if (count == 1) { $(this).parent().prev().find(".remove-me").remove(); $(this).parent().next().find(".remove-me").remove(); } $(this).parent().remove(); }); });

Related: See More


Questions / Comments: