Add and remove bootstrap custom fields by single clicks
index.html
file:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
<link rel="stylesheet" href="scripts/main.js"
<form id="surveyForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-xs-3 control-label">Options</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="option[]" />
</div>
<div class="col-xs-4">
<button type="button" id="addBttn" class="btn btn-default addButton">+</button>
</div>
</div>
<!-- The option field template containing an option field and a Remove button -->
<div class="form-group hide" id="optionTemplate">
<div class="col-xs-offset-3 col-xs-5">
<input class="form-control" type="text" name="option[]" />
</div>
<div class="col-xs-4">
<button type="button" class="btn btn-default deleteButton" onClick="removeElem(this);">-</button>
</div>
</div>
</form>
<script type="text/javascript">
// this will remove a custom filed on click
function removeElem(elem) {
console.log("element clicked ", elem);
$(elem).parents("div")[1].remove();
}
</script>
main.js
file:
$(document).ready(function(){
var i = 0;
$('#addBttn').click(function(){
orf = $('#optionTemplate')[0];
cf = orf.cloneNode(true);
cf.id = "custom_field" + ++i;
cf.className = "form-group";
orf.parentNode.appendChild(cf);
});
});
JSFiddle demo here