2
I have the following form:
<div class="col-md-12 form-group">
<div class="row" id="dep">
<div class="col-md-10">
<input type="text" class="form-control" placeholder="Nome do Dependente" id="dependente[]" name="dependente[]">
</div>
<div class="col-md-2">
<button class="btn btn-primary" type="button" id="adicionar_dependente"><span class="fa fa-plus"></span></button>
</div>
</div>
</div>
And I got the following jQuery:
$("#adicionar_dependente").click(function(){
var campos_novos = "<div class='col-md-10' id='dep_fc' style='margin-top: 5px;'><input type='text' class='form-control' placeholder='Nome do Dependente' id='dependente[]' name='dependente[]'></div><div class='col-md-2' id='dep_fc' style='margin-top: 5px;'><button class='btn btn-primary' type='button' id='deletar_dependente'><span class='fa fa-minus'></span></button></div>";
$("#dep").append(campos_novos);
});
$("#deletar_dependente").click(function(){
$(this).closest('#dep_fc').remove();
});
To add, it usually adds the lines inside the div, but to remove, it doesn’t work. Can anyone tell me where I’m missing?
Ids must be unique in the code, prefer
class
in these cases. Can you play something functional in CODEPEN? It would be better for us to test.– Bacco
When I add, the id name is dep_fc and when I remove too...
– Sr. André Baill
Try with
class
to see if anything changes. If you can put a demo on http://codepen.io it’s easy to test.– Bacco
http://codepen.io/anon/pen/KNYvxY
– Sr. André Baill
Ah, there’s one more problem, when you add a new #deletar_dependent, I don’t think jQuery will "hold" to the new control.
– Bacco
Exactly, it’s not worth it, because I click and it doesn’t delete... But I posted the code there
– Sr. André Baill
vc ta with 2 dep_fc in the same row when inserting, has more this. Probably the most practical thing would be to put an onclick inside the line, instead of using the jQuery selector, or by adding the new control, increasing a number in the ID. ai already solves the operation and the problem of repeated Ids.
– Bacco