How to make that jquery foreach does not repeat the data when I open model window?

Asked

Viewed 55 times

0

I have a window modal that when I open it carries me the data I need to have through a foreach jquery. Just close to modal and open again, all the data that comes from the foreach. How can I avoid it?

jquery

$(document).on("click", ".btn-add-agent-proximo", function(e) {
  if($('#add_agent').is(':checked')){ 
    $('#modal-add-agent').modal('hide'); 

    var id_agente_pai = <?= Auth::user()->id ?>

    $.ajax({
        type: "POST",
        url: "https://artslots.net/admin/list_agent",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: { id_agente_pai : 'id_agente_pai'},
        dataType: 'json'
    }).done(function( data ) {
        $.each(data.parents, function( key, parents ) {
            $('#parent').append('<option value="'+parents.id+'"><span>ID('+parents.id+') </span>'+parents.username+'</option>');
        });
        $.each(data.currencies, function( key, currencies ) {
            $('#currency').append('<option value="'+currencies.id+'">'+currencies.code+'</option>');
        });
        $.each(data.funcoes, function( key, funcoes ) {
            $('#funcoes').append('<option value="'+funcoes.id+'">'+funcoes.nome+'</option>');
        });

    }).fail(function(data) {
        toastr.error('Ocorreu um erro!');
    });

    $('#modal-add-agent-modal').modal('show');

  }else if($('#add_jogador').is(':checked')){ 
    $('#modal-add-agent').modal('hide'); 

      $.ajax({
        type: "POST",
        url: "https://artslots.net/admin/list_agent",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: { id_agente_pai : 'id_agente_pai'},
        dataType: 'json'
    }).done(function( data ) {
        $.each(data.parents, function( key, parents ) {
            $('#parent_jogador').append('<option value="'+parents.id+'"><span>ID('+parents.id+') </span>'+parents.username+'</option>');
        });

    }).fail(function(data) {
        toastr.error('Ocorreu um erro!');
    });

    $('#modal-add-jogador-modal').modal('show');
  }
});

1 answer

2


You can clear the data in the event that is triggered when the modal is closed, for example:

$('#modal-add-agent').on('hide.bs.modal', function () {
        ...
 });

Whenever you close the modal $('#modal-add-agent').modal('hide'); this event will be triggered, so you can use the empty() jquery, which removes all child nodes from the element you want.

ex:

$('#parent').empty();
  • Thanks was really that worked right

Browser other questions tagged

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