I have a text field with an add button next to it. The more I click the button it adds another text field with a remove button next to it. The idea is that when I click the successive remove buttons, it removes the text fields; but no matter what click, it does not work!
I would also like to know if there is a way to not use the e.preventDefault () command.
Using Chrome 56.0.2924.87, Bootstrap 3.2.1, Jquery 3.1.1 (JsFiddle here )
<form id="certameForm" class="form-horizontal" method="POST" action="teste_stack_overflow_01.php">
<div class="container">
<!-- Dt Pub DOM -->
<div class="form-group">
<div class="col-sm-11 inputGroupContainer">
<label class="col-sm-2 control-label">Dt Pub DOM</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="dt_pub_dom[]" name="dt_pub_dom[]" placeholder="Data de Pub. Dom." value="" />
</div>
<div class="col-sm-2">
<button class="btn btn-primary btn-md" id="add" name="add"><span class="glyphicon glyphicon-plus"></span></button>
</div>
</div>
</div>
<!-- Dt Pub DOM -->
<input type="hidden" id="id_pmc_reuniao" name="id_pmc_reuniao" value="">
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
var btCount = 1;
$('#add').on("click", function(e) {
btCount = btCount + 1;
e.preventDefault();
$(this)
.closest('div.form-group') // find the div with class '.forg-group'
.clone() // clone it
.insertBefore('#id_pmc_reuniao'); // and insert it before input text with id='id_pmc_reuniao'
$('.btn-md:last') // find the last button with class '.btn-md' and remove it
.remove();
$('.col-sm-2:last') // find the last div with class '.col-sm-2' and create another button but with the minus sign
.html('<button class=\"btn btn-primary btn-md\" id=\"n' + btCount + '\" name=\"n' + btCount + '\">\n\
<span class=\"glyphicon glyphicon-minus\"></span></button>');
});
$("button[id^='n']").
on('click', function() {
e.preventDefault();
alert('clicou');
});
});
</script>