I am creating a dynamic form that allows a user to add/remove text fields. While I can add text fields with no problem, I'm having difficulty removing specific text fields.
Whenever I add additional text fields (say a total of 5), and try to remove any of them except for the first one (say removing field 3). All of them disappear as if the page reloaded. It's as if my jQuery code doesn't run when "Remove Field" is pressed.
<form>
...
<div id="answers">
<div class="form-group" id="option1">
<div class="col-xs-11 col-sm-9 col-md-6">
<input class="form-control" id="answer" placeholder="Answer option">
</div>
<div class="col-xs-1 col-sm-1 col-md-1" style="line-height:36px;">
<a href="" class="remove">Remove Field</span></a>
</div>
</div>
</div>
...
</form>
<div>
<a href="" id="add">Add another field</a>
</div>
jQuery
<script>
$(document).ready(function() {
$( "#add" ).on( "click", function(event) {
event.preventDefault();
var options = $('#answers .form-group').length + 1;
$( "#answers div:first" ).clone()
.attr('id', 'option' + options)
.appendTo( "#answers" );
});
$( ".remove" ).on( "click", function(event) {
event.preventDefault();
$(this).closest(".form-group").remove();
});
});
</script>
Instead of this:
$( ".remove" ).on( "click", function(event) {
Try this:
$(document).on("click", ".remove", function(event) {