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

<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 ----------> <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"> <p id="count" ></p> <div class="control-group" id="fields"> <label class="control-label" for="field1">Fields</label> <div class="controls" id="profs"> <form class="input-append"> <div class="form-group"> <select class="custom-select mr-sm-2" id="field1"> <option selected>...</option> <option>service1</option> <option>service2</option> <option>service3</option> <option>service4</option> </select> </div> <button id="b1" class="btn add-more" type="button">+</button></div> <!--<div id="field"><input autocomplete="off" class="input" id="field1" name="prof1" type="text" placeholder="Type something" data-items="8"/>
* { .border-radius(0) !important; } #field { margin-bottom:20px; }
$(document).ready(function() { var next = 1; var selection = ['service1', 'service2', 'service3', "service4"]; var listService = []; //[{'id':next,'target_service':$('#field1').val()}]; console.log(listService); $(".add-more").on('click', function(e) { e.preventDefault(); var addto = "#field" + next; var addRemove = "#field" + (next); next = next + 1; var newIn = '<id="field" ><label>'; //newIn+='Veuillez choisir un service</label>'; newIn += '<select class="custom-select mr-sm-2" id=field' + next + '>'; newIn += ' <option selected>...</option>'; for (var i = 0; i < selection.length; i++) { newIn += '<option>' + selection[i] + '</option>'; } newIn += ' </select></div>'; var newInput = $(newIn); var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >-</button></div><div id="field">'; var removeButton = $(removeBtn); $(addto).after(newInput); $(addRemove).after(removeButton); $("#field" + next).attr('data-source', $(addto).attr('data-source')); $("#count").val(next); var value = $('#field' + (next - 1)).val(); listService.push({ 'id': next, 'target_service': value }); console.log(listService); }); $(document).on('click', '.remove-me', function(e) { e.preventDefault(); var fieldNum = this.id.charAt(this.id.length - 1); var fieldID = "#field" + fieldNum; $(this).remove(); $(fieldID).remove(); listService.splice(fieldNum - 1, 1); console.log(fieldNum); console.log(listService); }); });

Related: See More


Questions / Comments: