Adding and Removing jQuery Inputs

1

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 have 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 rows inside the div, but to remove, it does not work. Can anyone tell me where I'm going wrong?

    
asked by anonymous 22.12.2016 / 12:57

1 answer

2

I've seen two problems in your code.

  • You need a DIV to wrap your text field and its button, this DIV will be Parent and must have a class and not id . id can not repeat on page. So, because you can have multiple dependents, then you have to be class .

  • Dynamically created objects will not work the onClick function that you set for the button. You must delegate this function to document , and document is passed to the button that will be created.

  • $("#adicionar_dependente").click(function() {
      var campos_novos = "<div class='dep_fc'><div class='col-md-10' 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 remove' type='button' >Remove</button></div></div>";
      $("#dep").append(campos_novos);
    });
    
    $(document).on('click', 'button.remove', function() {
      $(this).closest('div.dep_fc').remove();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="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">ADD</button>
        </div>
      </div>
    </div>
        
    22.12.2016 / 13:09