Remove Dynamic Fields button

Asked

Viewed 79 times

0

I’m trying to make a button to remove a Dynamic field, my Add Field Button is working because I needed one to remove too so I have only button the function I could not create there

<!-- Select Basic -->
        <form>
          <div class="form-group" id="testescript">
            <label class="col-md-4 control-label" for="txtgrupo">Tramox </label>
            <div class="col-md-2">
              <select id=teste class="form-control">
                <option>#</option>
                <option>#</option>
              </select>
            </div>
          </div>
          <div class="col-md-8">
            <button type="button" id="add-campo" class="btn btn-primary">Adicionar Campo</button>
            <button type="button" id="rm-campo" class="btn btn-primary">Remover Campo</button>
          </div>
        </form>

        <br>

        <script>
          $("#add-campo").click(function() {

            $("#testescript").append('<div class="col-md-2"><select id=cbPais class="form-control"><option>#</option><option>#</option>);

          });
    </script>

1 answer

0

var start = 1;
$(".add").click(function() {
  $(".fields").append("<button class='btn btn-remove'>#" + start + " Clique para apagar</button>");
  start++;
});
$('body').on('click', '.btn-remove', function() {
  $(this).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='fields'>

</div>
<a href='#' class='add'>Adicionar Campo</a>

You can use an event to dynamically capture the elements:

$('body').on('click', '.campo-a-ser-removido', function() {
    $(this).remove();
});

follow ex no js fiddle https://jsfiddle.net/cq0zr7y2/

  • Didn’t work, buddy :(

  • note that . field-to-be-removed is the class of the field being added dynamically. in case you do not use class but an id then change to #cbPais

  • looks ex in jsfiddle that I added

Browser other questions tagged

You are not signed in. Login or sign up in order to post.